Skip to content

nguyenngocnhan90/Restful-Swift

Repository files navigation

Restful-Swift

RESTful service interaction in Swift iOS project.

Features

  • Request with dictionary param.
  • Request with object param RESTParam.
  • Request with multipart data (JSON, String, File).

Requirements

  • iOS 8.0 or later.

Installation

CocoaPods

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

Manually

If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire and SwwiftyJSON into your project manually.

Usage

Create data model SignInResult

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"]
    }
    
}

Create object param class

class SignInParam: RESTParam {
    var email: String!
    var password: String!
}

Invoker

  • 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)
    }
}

Contribution

If you see any problems or you want to make an improvement, please create Issues ans we can discuss.

Thanks