SweetCherry 1.2.1

SweetCherry 1.2.1

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Sep 2017
SwiftSwift Version 3.1
SPMSupports SPM

Maintained by Jakub Tudruj.



 
Depends on:
Alamofire~> 4.5
ObjectMapper~> 2.2
 

  • By
  • Jakub Tudruj

SweetCherry is small library that helps implement Rest API communication in your project. SweetCherry uses Alamofire and ObjectMapper.

Minimum requirements

  • iOS 8.0+
  • macOS 10.10+
  • watchOS 2.0+
  • tvOS 9.0+

Usage

Configuration

//REST API endpoint with "/" suffix
SweetCherryConfig.shared.url = "https://example.com/api/" 
//Standard HTTP headers included to every request
SweetCherryConfig.shared.standardHeaders = ["os": "ios", "language" : "en"]
//Authorisation headers
SweetCherryConfig.shared.authHeaders = ["AuthToken": "xyz123", "DeviceId" : "abcd1234"]
//Set logger object that conforms to ApiLoggable protocol
SweetCherryConfig.shared.register(logger: Logger.shared) 

//array of valid response HTTP status codes
SweetCherryConfig.shared.validResponse.statusCodes = Array(200..<301) 
//aray of accetable response content types
SweetCherryConfig.shared.validResponse.contentType = ["application/json", "text/html"]
//dictionary containing required key value pairs
SweetCherryConfig.shared.validResponse.jsonContainsKeyValuePairs = ["status" : "success"]
//array of required response keys
SweetCherryConfig.shared.validResponse.jsonContainsKeys = ["encriptionKey"]

//closure called after every success response
/*
* (DEPRECATED! Use mainCompletion instead)
*/
SweetCherryConfig.shared.mainSuccess = { dataResponse in
  if let headers = dataResponse.response?.allHeaderFields {
      print("Headers:\n\(headers.description)")
  }
}

//closure called after every failure response 
/*
* (DEPRECATED! Use mainCompletion instead)
*/
SweetCherryConfig.shared.mainFailure = { error, dataResponse in
  print("Error: \(error)"
}

//closure called after every response

SweetCherryConfig.shared.mainCompletion = { result, data in
  switch result {
  case .success(let entity):
    print("Success: \(entity)")
  case .failure(let error):
    print("Failure: \(error)")
  }
}

Request & Response

Required imports:

import Alamofire
import ObjectMapper
import SweetCherry

example request with methods chaining

/*
* (DEPRECATED! Use start(completion: CompletionHandler<Entity>) instead)
*/
class User {
    class func list(success: @escaping SweetCherry.SuccessHandler<ResponseEntityClass>, failure: @escaping SweetCherry.FailureHandler) {
        SweetCherry(method: .get, action: "users/list")
            .parameters(["xxx" : "yyy"])
            .requireAuth()
            .start(success: success, failure: failure)
    }
}
/*
* (DEPRECATED! Use start(completion: CompletionHandler<Entity>) instead)
*/
class ViewController {
    User.list(success: { (responseEntity, data) in
        print("Success: \(responseEntity)")
    }, failure: { (error, data) in
        print("Failure: \(error)")
    })
}

OR

/*
* (DEPRECATED! Use start(completion: CompletionHandler<Entity>) instead)
*/
SweetCherry(method: .get, action: "users/list")
    .parameters(["xxx" : "yyy"])
    .parameters(requestEntity) //object of class that conforms to Mappable
    .requireAuth()
    .start(success: { (responseEntity: ResponseEntityClass, data) in
        print("Success: \(responseEntity)")
    }, failure: { (error, data) in
        print("Failure: \(error)")
    })

New method:

class User {
    class func list(completion: @escaping SweetCherry.CompletionHandler<ResponseEntityClass>) {
        SweetCherry(method: .get, action: "users/list")
            .parameters(["xxx" : "yyy"])
            .requireAuth()
            .start(completion: completion)
    }
}

class ViewController {
    User.list(completion: { result, data in
     switch result {
     case .success(let entity):
       print("Success: \(entity)")
     case .failure(let error):
       print("Failure: \(error)")
     }
   }
    
    
}

OR

SweetCherry(method: .get, action: "users/list")
    .parameters(["xxx" : "yyy"])
    .parameters(requestEntity) //object of class that conforms to Mappable
    .requireAuth()
    .start { (result: SweetCherry.Result<ResponseEntityClass>, data) in
      switch result {
      case .success(let entity):
        print("Success: \(entity)")
      case .failure(let error):
        print("Failure: \(error)")
      }
    }

methods description

Init with method - Alamofire HTTPMethod:

  • .get (default)
  • .post
  • .put
  • .delete
  • .head
  • .patch
  • .trace
  • .connect

and API action name (String)

SweetCherry(method: .get, action: "users/list")

or

SweetCherry(action: "users/list") //default method: get

Parameters

method parameters as dictionary

parameters(_ dictionary: Parameters)

or Mappable (ObjectMapper) object

parameters(_ object: Mappable)

Authorisation

Include auth headers from config to request

requireAuth(_ requireAuth: Bool = true)

Custom config

Include custom config to request

load(config: SweetCherryConfigurable)

Start reuest

Start request.

.start { (result: SweetCherry.Result<Mappable>, data) in
  switch result {
  case .success(let entity):
    //success
  case .failure(let error):
    //failure
  }
}