Calling Objective-C from Swift

Until recently I hadn’t had to do this, but I was surprised at how easy it was. There is an excellent post that provides a walkthrough on this over at stackoverflow here.

In summary, the main steps are:

1. Add the Objective-C files to your project (drag and drop), and when prompted to configure an Objective-C bridging header, hit Yes! For example purposes, let’s call the file we’re importing “TestClass”.

2. In the newly created bridging header file (it will be in the format “YourProject-Bridging-Header.h”), add a line: import “TestClass.h”.

3. Then inside a Swift class, all you need to add is: var instanceOfTestClass:TestClass = TestClass()

And that’s it, easy!

Fetch custom photo album using Swift

I had a project recently where I had to parse the photos inside a photo album at runtime. The code for this is surprisingly simple, but if you’ve never done it before it can be an interesting challenge in Swift.

When loading a custom photo album on iOS, we’re in fact fetching a PHAssetCollection that matches a given string. The given string when searching for an album is the album title as it appears in the Photos app. Use the following code to fetch the collection:

Say the app also needs to create the photo album, e.g. if the album does not exist. In order to do this, we can use the following code: