Today I Learned How to Create a Xamarin iOS Binding for Objective-C Libraries – Part 3 Using Sharpie to Create Binding Interface

This is the 3rd part about using the BEMCheckBox, an Objective-C library, in Xamarin.  Part 1 described how to compile the BEMCheckBox library using Xcode.  Part 2 showed how to combine the multiple libraries we compiled from Part 1 into one library.  In this part I’ll describe how to use Sharpie to create the C# API interface.

Sharpie is a tool that reads the header files in the BEMCheckBox framework and extract a C# interface.  We could create the interface manually but it’s easier if we let technology do some of the work for us.  Don’t worry about this job being replaced by a robot as we will have to manually edit the file after it’s generated, at least for BEMCheckBox.  Download the sharpie tool here and read more about the sharpie here.

Remember this screen shot from Part 2 where we merged two libraries into one?

Lipo Command Screen Shot

This is the library we created that supports multiple architectures (x86, x64, Arm7, Arm64).  We need to run Sharpie on this the header files in this single framework.  Open up the terminal and run this command to see what sdk versions are installed.

sharpie xcode -sdks

This will show something like:

sdk: appletvos10.2    arch: arm64
sdk: iphoneos10.3     arch: arm64  arm7
sdk: macosx10.12      arch: x86_64 i386
sdk: watchos3.2       arch: arm7k

Once you know the iphone sdk version you can run the actual sharpie command.  Run this command against the header files in the BEMCheckBox framework folder.

sharpie bind -sdk iphoneos10.3 BEMCheckBox.framework/Headers/BEMCheckBox.h

The output should look something like:

Parsing 1 header files...

Binding...
  [write] ApiDefinitions.cs
  [write] StructsAndEnums.ca

Submitting usage data to Xamarin...
  Submitted - thank you for helping to improve Objective Sharpie!

Done.

A screen shot of the commands is below.

Sharpie Command

This should generate two files for BEMCheckBox: ApiDefinitions.cs and StructsAndEnums.cs.  For other libraries you might only get one file.

Go ahead and look at the files now.  In the APIDefinitions file you will C# interfaces with a bunch of attributes.  The interface maps the methods in the objective-c header file.  In the StructsAndEnums file you will see enums used by BEMCheckBox.  A snippet of the files is shown below.

API Definitions:

// @interface BEMCheckBox : UIControl <CAAnimationDelegate>
[BaseType(typeof(UIControl), Delegates = new string[] { "WeakDelegate" }, Events = new Type[] { typeof(BEMCheckBoxDelegate) })]
interface BEMCheckBox
{
  [Export("initWithFrame:")]
  IntPtr Constructor(CGRect frame);

  [Wrap("WeakDelegate")]
  [NullAllowed]
  BEMCheckBoxDelegate Delegate { get; set; }

  // @property (nonatomic, weak) id<BEMCheckBoxDelegate> _Nullable delegate __attribute__((iboutlet));
  [NullAllowed, Export("delegate", ArgumentSemantic.Assign)]
  NSObject WeakDelegate { get; set; }

  // @property (nonatomic) BOOL on;
  [Export("on")]
  bool On { get; set; }

  // @property (nonatomic) CGFloat lineWidth;
  [Export("lineWidth")]
  nfloat LineWidth { get; set; }

  // Other methods...

}

Structs:

[Native]
public enum BEMBoxType : long
{
  Circle,
  Square
}

[Native]
public enum BEMAnimationType : long
{
  Stroke,
  Fill,
  Bounce,
  Flat,
  OneStroke,
  Fade
}

This is all well and good but an interface can’t make calls to the underlying objective-c interface.  I’ll discuss how Visual Studio auto-magically creates the wiring between the C# interface and the BEMCheckBox library in Part 4.  For now go ahead and get another cookie.  You deserve it.

Don’t forget you can find a working example of BEMCheckBox in Xamarin iOS here.

 

P.S. – A classic Cookie Monster song about up and down.  Can you figure out what happened to Cookie Monster’s cookie before the end of the song?

Save

Posted in Code Examples, Software Development, Today I Learned | Tagged , , , , , , | Comments Off on Today I Learned How to Create a Xamarin iOS Binding for Objective-C Libraries – Part 3 Using Sharpie to Create Binding Interface

Kids Thinking Outside the Box – Favourite Cheese

Transcript of my wife talking to my daughter’s grade 6 friend:

Wife: “What is your favourite cheese?”

Friend: “Grated!”

Posted in Fun, Kids Thinking Outside the Box | Tagged | Comments Off on Kids Thinking Outside the Box – Favourite Cheese

Today I Learned How to Create a Xamarin iOS Binding for Objective-C Libraries – Part 2 Combining Libraries

This is part 2 of creating a iOS Binding for the Objective-C Library BEMCheckBox.  In part 1 we compiled the Xcode project into two separate libraries.  One for iphones (ARM architecture) and one for iOS simulators (x86/x64 architecture).

In this post I’ll discuss how to combine two libraries into one that contains all the architectures.  If you fail to combine the libraries then you will get errors when you bind to Xamarin.  If you only have the iphone library then it won’t run on the simulator and vice versa.

Just a reminder that you should have the Release-iphoneos and Release-iphonesimulator builds as shown below.

Compiled Frameworks In Finder

To combine the libraries requires the use of the lipo tool.  Before we lipo these libraries we first need to get setup.  To start with copy the Release-iphoneos/BEMCheckBox.framework folder to the Products folder as shown below.

Copy BEMCheckBox Framework

Results Of Copying BEMCheckBox Framework

It actually doesn’t matter if you copy the iphone or simulator folder.  Inside that folder is the compiled library along with some other such as uncompiled header files.  The library file can be found at BEMCheckBox.framework/BEMCheckbox.  This file will be different between the iphone and simulator releases but the header files will be the same.

Our goal is to replace the BEMCheckbox compiled library that only supports ARM with one that supports all the architectures.  This is where we use lipo.  Open up a terminal window on your Mac and navigate to the Products folder.  Then enter the following command:

lipo -create -output BEMCheckBox.framework/BEMCheckBox Release-iphoneos/BEMCheckBox.framework/BEMCheckBox Release-iphonesimulator/BEMCheckBox.framework/BEMCheckbox

This will combine the iphone and simulator libraries into one library and replace the one we in the products folder with the combined one.  To make sure everything worked as expected run the file command as shown below.

file BEMCheckBox.framework/BEMCheckBox

You should get the following output or something similar:

BEMCheckBox.framework/BEMCheckBox: Mach-0 universal binary with 4 architectures: [i386: Mach-0 dynamically lined shared library i386]&amp;nbsp;[x86_x64: Mach-0 dynamically lined shared library x86_x64]&amp;nbsp;[arm_v7: Mach-0 dynamically lined shared library arm_v7]&amp;nbsp;[arm64: Mach-0 dynamically lined shared library arm64]
BEMCheckBox.framework/BEMCheckBox (for architecture i386): Mach-0 dynamically linked shared library i386
BEMCheckBox.framework/BEMCheckBox (for architecture x86_x64): Mach-0 dynamically linked shared library x86_x64
BEMCheckBox.framework/BEMCheckBox (for architecture arm_v7): Mach-0 dynamically linked shared library arm_v7
BEMCheckBox.framework/BEMCheckBox (for architecture arm64): Mach-0 dynamically linked shared library arm64

You can also use the lipo command tool to check the library.

lipo -info BEMCheckBox.framework/BEMCheckBox

You should see something like:

Architectures in the fat file: BEMCheckBox.framework/BEMCheckBox are: i386, x86_x64, arm7, arm64

A screen show of all the commands looks like:

Lipo Command Screen Shot

We now have one library that will work with Xamarin and both iOS simulators and physical iPhones.  Like combining a chocolate and peanut butter cookie.  In Part 3 I’ll explain how to create the binding between this delicious chocolate and peanut butter cookie and Xamarin.  Finally you can find a working example of BEMCheckBox in Xamarin iOS here.

 

P.S. – Not a song this time but a cookie monster skit that makes me laugh.

Posted in Code Examples, Software Development, Today I Learned | Tagged , , , , | Comments Off on Today I Learned How to Create a Xamarin iOS Binding for Objective-C Libraries – Part 2 Combining Libraries

Today I Learned How to Create a Xamarin iOS Binding for Objective-C Libraries – Part 1 Compiling the Objective-C Library

There is no checkbox for Xamarin Forms applications.  This is a problem because I wanted a checkbox in a application I’m working on.  A switch wasn’t going to cut it.

After a bit of research I found that Android had native checkbox.  Half my problem was solved.  I celebrated by eating a cookie.

Then I ran into a problem because iOS does not have a native checkbox control.  I found others had solved this problem by creating a iOS button and adding a checkbox image to it.  One image for checked and one for unchecked.  This works but it means I can’t easily change the colour, size, etc. of the checkbox.  Any changes would require me to create new images.  Using MS Paint or GIMP is not my strong suit.

Then I found BEMCheckBox which does everything I need it to.  It also allows for circle and square checkboxes.  But wait, BEMCheckBox is in Objective-C.  How does I reference it in my Xamarin project?  Native bindings to the rescue!

Step one is compile the native library using Xcode.  Download the code and open it in Xcode.  Then make sure the project is being built for release.  If you are like me and not very familiar with Xcode the exact steps are:

  1. Click the BEMCheckBox project and choose edit schema.  In the dialog pick Run on the left and Info in the middle.
  2. Then change the build configuration to Release.

Next we need to build the library.  Actually we need to build it twice, once for the iOS simulators (x86 and x64 architectures) and once for physical iOS devices (ARM architectures).  To build for a iOS device make sure the area beside the BEMCheckBox says Generic iOS Device.  Then pick Product->Build For->Running from the menu.

Build For iOS Device

Then switch the Generic iOS Device to any iOS simulator and do the same thing.

Build For iOS Simulator

To find the two builds you just created right click on the BEMCheckBox.framework in the Products folder and choose Show in Finder.

Show Compiled Framework In Finder

You should see both a Release-iphoneos and Release-iphonesimulator folders.   You might also see Debug-<os> folders but you can ignore those.

Compiled Frameworks In Finder

That is it for part 1.  Good work, help yourself to a cookie.  In part 2 we will combine the two libraries into one.  If you don’t combine the builds then the library will only work on the simulators or physical devices in Xamarin not both.  Obviously we want the framework to work with both.  Finally you can find a working example of BEMCheckBox in Xamarin iOS here.

 

P.S. – I really like cookies.  They are my favourite desert dessert.

P.S.S. – Why is desert and dessert so similar?

Chocolate pudding
It no phase me
But you got cookie
So share it maybe

Save

Posted in Code Examples, Software Development, Today I Learned | Tagged , , , , | Comments Off on Today I Learned How to Create a Xamarin iOS Binding for Objective-C Libraries – Part 1 Compiling the Objective-C Library

You Can’t Just Turn Creativity On Like A Faucet

Lately, Chris has been working on Xamarin notifications in Android, which you would have gathered from his recent blog posts. I have been tasked with designing an icon to go with this work. I’ve designed a few things before (Scary Sun being my best work), but this task seemed to be especially vexing.

How would I come up with something that captures the concepts of Xamarin, Saturday Morning Productions,  and notifications? It seemed like a lot to fit into a very small space. Now, when I think of being notified for something, I immediately think of bells. Like alarm clock bells. I drew a few iterations of an icon with a bell, but honestly, they looked kinda dumb. I’m not sure anyone would look at them and connect the three things together that I just mentioned. I wondered if I would get a flash of inspiration if I just let it percolate around my brain a bit.

The problem with that approach is that time becomes a very loose concept. Before I knew it, a whole week had passed. Tricky things, those weeks. I had to send something to the team! I started at a blank piece of paper, hoping creativity would find me.

I looked at the Xamarin logo again. You know, I could probably make that shape into an alarm clock…I thought. So I drew some legs and bells on the Xamarin logo and added some music notes. You know, to imply sound. But how to fit in the SMP reference? After a chat with Ada and Chris, they suggested turning “SMP” into musical notes themselves. It’s just crazy enough that it might work, I mused. They were right. Even thought it wasn’t my proudest moment for leaving something to the last minute, I am pleased with the results.

And, just for good measure, here is the Calvin & Hobbes post that inspired this post!

(Source: Calvin & Hobbes. These days Calvin and Hobbes seem to sum up most of my concepts!)

Posted in Fun, Uncategorized | Comments Off on You Can’t Just Turn Creativity On Like A Faucet

Today I Learned How to Handle Local Notifications in Xamarin on Android

In my previous example I detailed how to schedule notifications in Xamarin on Android but didn’t show the Xamarin Forms application reacting to that specific notification.  Let’s fix that.

First override the OnNewIntent method in the MainActivity.  We override this method so notifications will work if the application is currently running or is stopped and the notification started the application.  In the OnNewIntent method you put code that makes sure it’s a notification you want to respond to then extracts any needed information from the notification.  An example is below:

protected override void OnNewIntent(Intent intent)
{
  // Let the parent do it's thing.
  base.OnNewIntent(intent);

  // Is this a notification intent? The action should look like:
  //
  // &amp;amp;lt;packagename&amp;amp;gt;.NOTIFICATION-&amp;amp;lt;ID&amp;amp;gt;
  //
  var expectedActionName = BuildActionName("");
  if (intent.Action == null || !intent.Action.StartsWith(expectedActionName))
  {
    // Not a notification intent. Do nothing.
    return;
  }

  // Extract the notification information.
  var extractedNotification = new Notification
  {
    Id = intent.Action.Substring(intent.Action.IndexOf("-", StringComparison.Ordinal) + 1), // The ID is part of the action. 
    Title = intent.GetStringExtra(TitleExtrasKey), // These fields are extras but should exist.
    Message = intent.GetStringExtra(MessageExtrasKey) // These fields are extras but should exist.
  };

  // Do whatever you want with the notification.
  NotificationRecieved(extractedNotification);
}

The first thing the method does is check if it’s a notification we are interested in.  In this example we know that notifications we are interested in have a certain action name so we check for that.

var expectedActionName = BuildActionName("");
if (intent.Action == null || !intent.Action.StartsWith(expectedActionName))
{
  // Not a notification intent. Do nothing.
  return;
}

Next we extract the notification information.  In this case we only pull out the ID, title, and message but you could add other things as needed.

var extractedNotification = new Notification
{
 Id = intent.Action.Substring(intent.Action.IndexOf("-", StringComparison.Ordinal) + 1), // The ID is part of the action. 
 Title = intent.GetStringExtra(TitleExtrasKey), // These fields are extras but should exist.
 Message = intent.GetStringExtra(MessageExtrasKey) // These fields are extras but should exist.
};

Finally do whatever you want with this the notification.  This could be showing a certain screen in your application, updating some data, etc.  In this example we just call a handling method and leave it up to your very vivid imagination.

If you want a working example checkout the XPlugins.Notifications plugin.  If you are writing an Xamarin Forms application you can use the plugin to handle notifications in both Android and iOS.

P.S. – Another post about communication and another music video about communication.  The song is not about communication but the video is.  Just watch it and you will figure it out.

P.P.S. – This is the only song I can play on guitar and sing at the same time.  Both poorly.

 

 

 

Posted in Code Examples, Today I Learned | Tagged , , , , | Comments Off on Today I Learned How to Handle Local Notifications in Xamarin on Android

Simplify, Simplify…

The great philosopher Henry David Thoreau once said: “Simplify, simplify.”

I actually didn’t know that Thoreau said that until I saw a reference to that quote in a Calvin & Hobbes comic. But that’s another story.

You might be wondering why we at Saturday Morning Productions haven’t written any blog updates about our Goal Buddy App project. Well, that’s because we have reached a bit of an impasse. Our master-coder Chris has written quite a few updates on the first version, which focused on scheduling tasks and having reminders for those tasks. It was cool seeing the app come together. But we started to wonder: how was this any different than using a calendar app?

It was time to take a big step back. Was it an instance of not seeing the forest for the trees? Or maybe Goal Buddy needed to be follow Thoreau’s advice and simplify. Here’s what we did. Chris pared the app back to a bare-bones state to focus on just accomplishing three goals per day. The thinking behind this is that focusing on a small and achievable set of daily goals reinforces positive choices for getting things done. (I like to joke that I can remember three important things per day. If I have to remember anything else, something inevitably gets bumped out of the queue!) The beauty of this approach is that, like the app itself, it is simple, straightforward, and realistic.

Perhaps with the original iteration of Goal Buddy, we had too much complexity right off the bat. Approaching it from this simpler stance will allow us to see what would make for useful additions for future versions. I guess we will be taking Thoreau’s (and Calvin’s parents’) advice!

(source: gocomics.com)

Posted in Fun, Goal App | Comments Off on Simplify, Simplify…

First Beta Release of the Xamarin Notification Plugin (Version 0.3.0-RC2)

The first beta version of the Xamarin Notification Plugin has been released.  This plugin allows you to send local notifications easily using Xamarin.  You can find the release on NuGet under “SaturdayMP.XPlugin.Notifications“.

More details and documentation can be found on the GitHub page.  You can provide feedback to us (bugs, features, etc) by entering a issue here.  Finally if you want the bleeding edge check out the MyGet feed.

Posted in Uncategorized | Comments Off on First Beta Release of the Xamarin Notification Plugin (Version 0.3.0-RC2)

So Long For Now, Our Original Goal Buddy

Chris and I are late to the party, bidding our fond farewells to Stuart McLean.  But it wouldn’t be right to not pay our respects to the person who motivated us through many a chore.

Long before Saturday Morning Productions or Goal Buddy were even conceived, we were spending our Saturday mornings building a cold storage room under the stairs in our then-new house.  We can honestly say it is the opening riff of the theme music and the sound of the storyteller’s voice that encouraged us to get sawing and painting.  We even emailed him back then to let him know the impact he had on our routine.  Years later, during jam-making and harvest seasons, we have his show to thank for the completed room.

Years later, the excitement of home ownership hadn’t faded, but the thrill of housework had lost its shine, especially with our small family and the company to run during the week.  Saturday mornings became the time for  tedious tasks like cleaning bathrooms and filing.  It was Stuart’s voice that made those mornings less unpleasant – that spoonful of sugar, if you will.

We’re thankful we can still listen to old favourites on the podcast.  Not only does it get us through whatever Saturday mornings mean to us now, it serves as a reminder of what can be accomplished with a little push.

Posted in Fun, Goal App | Comments Off on So Long For Now, Our Original Goal Buddy

Stack Overflow Developer Survey 2017

Stack Overflow Developer Survey Results 2017

The results of the Stack Overflow Developer Survey 2017 are live.  Some surprising highlights for me:

  • Most developers surveyed are white male web developers.  Just kidding, this was not surprising at all.
  • More than 50% of developers’ parents had a university degree of some type.  I wonder what the parent’s education level is like for other occupations?
  •  SQL is the 2nd most popular programming language.  Surprising to me because I don’t think of SQL as a programming language. Not sure why.  Maybe because you don’t run a SQL application but an application that uses SQL.  Guess I have to change my thinking.
  • Most dreaded language is VB6 which is what I started my professional career with.  Not sure why people dislike it so much.  Maybe it has more to do with the fact most VB6 projects are old and it’s hard to get a VB6 development environment setup.
  • The most dreaded platform is Sharepoint, which is something I’ve never liked and actively avoid.  Glad it’s not just me.
  • Visual Studio is a very popular IDE but the second most popular was Notepad++.  I assume that everyone has Notepad++ installed on their workstation.  Unless you are a sysadmin then you like Vim.  Don’t forget to quit Vim it’s Esc-q or Esc-wq if you want to save and quit.
  • Most developers outside of the United States are underpaid when you translate their salary to USD.  I wonder if this is because of the currently strong US dollar and if the difference wouldn’t have been so high 5 years ago.
  • Git won the version control war over Mercurial despite me personally liking Mercurial better.  Surprisingly Subversion is used more than Mercurial.

Save

Posted in Software Development, Uncategorized | Tagged , , | Comments Off on Stack Overflow Developer Survey 2017