Swift & Cocoapods
How to integrate Cocoapods into a vanilla Swift project
So, everyoneâs excited about the Objective-C successor Apple unveiled yesterday. After the rush to download Xcode 6 you created your first swift project and start hacking away, but your code feels alone. It wants to play with all the great libraries out there, so quick! Letâs add some pods!
First you create a Podfile:
platform :ios, '7.0'
pod 'AFNetworking', '~> 2.2.4'
and run pod install to find your pods nicely integrated with your project.
But how to talk to your Objective-C pods from your Swift files? What to import and where?
Apple shows how to mix ân match Objective-C and Swift mentions the bridging header. Thatâs exactly what youâre missing. So hurry, letâs create one!
Create a new header file and reference it from your build settings
This fileâs where the magic happens. Import everything you want to access from your Swift code inside the bridging header:
#import <AFNetworking/AFNetworking.h>
From now on you can use your favorite libraries from your new favorite programming language:
let manager = AFHTTPRequestOperationManager()manager.GET(
"http://example.com/resources.json",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
})
Big success!
Not so fast though. If youâre like me and you longed to see how the ReactiveCocoa syntax fits into Swift youâre going to run into trouble. Appearently thereâs a bug that causes the compilation to fail on RACSignals not, and and or methods. Letâs hope this will be fixed soon.
Until then, happy Swifting! And go watch some courses on functional programming while youâre at.