Sharing the Code

Programming stuff that might be useful to others

RestKit and Swift

RestKit is an iOS library that helps when working with REST web services. It will convert your classes to/from JSON and integrates with Core Data. I’ve added some code on top of RestKit to automate the creation of mappings and routes so your final code kind of ends up looking like your Rail’s routes:

[sourcecode]
addRoutesForClass(Country.self, only:Index)
[/sourcecode]

Once you’ve done the mapping from camel case to underscore case, it works quite well with a Rails REST API and Active Model Serializer. But there are one or two gotchas you have to look out for when working in Swift. After generating your NSManaged classes you will need to make some changes to the generated code. @objc(ClassName) needs to be prefixed to the model class so that RestKit can use NSClassFromString:

[sourcecode]
@objc(Country) class Country:NSManagedObject {
@NSManaged var name: NSString
}
[/sourcecode]

Also string properties will need to be changed from String to NSString.

Initially I called my generated class _Country and extended it with a class called Country that included my own code but it didn’t like that so I had to just use one class which means any changes to the model require manual changes to the NSManaged classes.

There was some code I was unable to do in Swift. For example:

[sourcecode]
[RKRoute routeWithClass:objectClass pathPattern:pathPattern method:method]
[/sourcecode]

would written as a constructor in Swift:

[sourcecode]
RKRoute(class:objectClass, pathPattern:pathPattern, method:method)
[/sourcecode]

But it didn’t like the use of class as a parameter name.

I also wasn’t able to set logging in Swift because of the use of preprocessor macros in RestKit so again I had to write it in Objective-C. I wrote both of these as class methods and called them from my Swift code:

[sourcecode]
@implementation RestKitObjC

+ (void) initLogging{
RKLogConfigureByName(“RestKit/ObjectMapping”, RKLogLevelDebug);
RKLogConfigureByName(“RestKit/CoreData”, RKLogLevelTrace);
}

+ (RKRoute *) routeWithClass:(Class)objectClass pathPattern:(NSString *)pathPattern method:(RKRequestMethod)method{
return [RKRoute routeWithClass:objectClass pathPattern:pathPattern method:method];
}

@end
[/sourcecode]

Comments are closed