RESTful service interaction in Swift iOS project.
- Create request with Alamofire.
- Return JSON with SwiftyJSON.
- Parse JSON to Swift object automacally with ObjectMapper.
- Request with dictionary param.
- Request with object param RESTParam.
- Request with multipart data (JSON, String, File).
- iOS 8.0 or later.
- Copy
Restful
folder to your project manually. - Install Alamofire, SwiftyJSON and ObjectMapper.
CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:
$ gem install cocoapods
To integrate Alamofire and SwiftyJSON into your Xcode project using CocoaPods, specify it in your Podfile
:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Alamofire'
pod 'SwiftyJSON'
pod 'ObjectMapper'
Then, run the following command:
$ pod install
If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire and SwwiftyJSON into your project manually.
class SignInResult: RESTObject {
var access_token: String?
var user: User?
override func mapping(map: Map) {
access_token <- map["access_token"]
user <- map["user"]
}
}
class User: RESTObject {
var email: String = ""
var first_name: String = ""
var last_name: String = ""
override func mapping(map: Map) {
email <- map["email"]
first_name <- map["first_name"]
last_name <- map["last_name"]
}
}
class SignInParam: RESTParam {
var email: String!
var password: String!
}
- Init invoker with a controller:
init() {
super.init(controllerName: "sessions")
}
- Make a request to sign in and parse response to
SignInResult
object
func signIn(param: SignInParam, completion: (result: SignInResult?, error: RESTError?) -> Void) {
let request = requestWithMethodName(nil)
request.POST(param) { (result: SignInResult?, error) -> () in
completion(result: result, error: error)
}
}
If you see any problems or you want to make an improvement, please create Issues ans we can discuss.
Thanks