SweetCherry 1.2.1

SweetCherry 1.2.1

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布上次发布2017年9月
SwiftSwift 版本3.1
SPM支持 SPM

Jakub Tudruj 维护。



 
依赖
Alamofire~> 4.5
ObjectMapper~> 2.2
 

  • Jakub Tudruj

SweetCherry 是一个小巧的库,帮助在项目中实现 Rest API 通信。SweetCherry 使用 Alamofire 和 ObjectMapper。

最低要求

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

使用方法

配置

//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)")
  }
}

请求数据和响应数据

所需导入

import Alamofire
import ObjectMapper
import SweetCherry

通过方法链的示例请求

/*
* (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)")
    })
}

或者

/*
* (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)")
    })

新方法

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

或者

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

方法描述

使用 method 初始化 - Alamofire HTTPMethod

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

以及 API 动作名称 (String)

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

或者

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

参数

将方法参数作为 JSON 对象使用字典

parameters(_ dictionary: Parameters)

或者作为 Mappable (ObjectMapper) 对象

parameters(_ object: Mappable)

授权

将配置中的 aut headers 包含到请求中

requireAuth(_ requireAuth: Bool = true)

自定义配置

将自定义配置包含到请求中

load(config: SweetCherryConfigurable)

启动请求

启动请求。

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