Pro Yearly is on sale from $80 to $50! »

Tiny Networking in Swift

Tiny Networking in Swift

Ade0c334ecff1448bb96f5f733bf1f83?s=128

Chris Eidhof | @chriseidhof

December 09, 2014
Tweet

Transcript

  1. Tiny Networking @chriseidhof

  2. $ pod install AlamoFire

  3. Live coding!

  4. $ rake routes | grep sign_in ... api_user_session POST /api/users/sign_in(.:format)

  5. $ curl "http://localhost:3000/api/users/sign_in" \ -d "{\"email\": \"chris@eidhof.nl\", \"password\": \"testtes\"}" \

    --header "Content-Type:application/json" \ {"message":"Error with your login or password"}~
  6. $ curl "http://localhost:3000/api/users/sign_in" -d "{\"email\": \"chris@eidhof.nl\", \"password\": \"testtest\"}" --header "Content-Type:application/json"

    {"auth_token":"8yBZFpqhagTJr6DpDSyS","email":"chris@eidhof.nl"}
  7. func apiRequest<A>( baseURL: NSURL, resource: Resource<A>, failure: () -> (),

    completion: A -> () )
  8. struct Resource<A> { let path: String let method : Method

    let headers : [String:String] let requestBody: NSData? let parse: NSData -> A? }
  9. typealias JSONDictionary = [String:AnyObject] func decodeJSON(data: NSData) -> JSONDictionary? func

    encodeJSON(dictionary: JSONDictionary) -> NSData?
  10. Usage

  11. let parse : NSData -> String? = { data in

    if let jsonDict = decodeJSON(data) { return jsonDict["auth_token"] as? String } return nil }
  12. let requestParameters = ["email": "chris@eidhof.nl", "password": "testtest"] let jsonBody =

    encodeJSON(requestParameters)
  13. let path = "api/users/sign_in" let headers = ["Content-Type": "application/json", "Accept":

    "application/json"] let resource = Resource(path: path, method: .POST, requestBody: jsonBody, headers: headers, parse: parse)
  14. let baseURL = NSURL(string:"http://localhost:3000")! apiRequest(baseURL, resource, { println("failure") }, {

    authorizationToken in println("Auth token \(authorizationToken)") })
  15. let email = "chris@eidhof.nl" let password = "testtest" let baseURL

    = NSURL(string:"http://localhost:3000")! let resource = login(email, password) apiRequest(baseURL, resource, { println("failure") }, { authorizationToken in println("Auth token \(authorizationToken)") })
  16. More live coding!

  17. Resources — https:/ /gist.github.com/chriseidhof/ 26bda788f13b3e8a279c — http:/ /chris.eidhof.nl/posts/tiny-networking-in- swift.html —

    http:/ /www.objc.io/books/
  18. Thanks?

  19. None
  20. None
  21. None
  22. None
  23. None