Zero: Update 2018.5

Swift 4.0 introduces a new language feature called Codable that makes it easier to convert objects and their representations to and from one another in tandem. See juejin.cn/book/684473… Article 2. The new practice using enumerated in swift unified management project Api “www.jianshu.com/p/32c99a3aa…

One: Tool introduction

1.Alamofire(Github address): There has been a detailed analysis of Alamofire(link address) 2.HandyJSON(Github address): Ali open source tool for instance and JSON mutual conversion, its implementation principle is not based on KVC, So he doesn’t require the instance to inherit from NSObject, nor does he need to implement the mapping method. HandyJSON currently relies on memory rules inferred from the Swift Runtime source code and any changes will be kept up to date. HandyJSON and ObjectMapper(Github address) feature comparison:

Both support structs, both support serialization and deserialization; HandyJSON does not need to implement the mapping method, ObjectMapper does; HandyJSON supports type adaptation, ObjectMapper does not. HandyJSON enum support; .Copy the code

3. Model uses structures instead of classes. In the Swift standard library, about 90 percent of the exposed types are structs. details on the difference between structs and classes will be learned in Swift Advanced Structs and classes.

Two: frame building

1. The statement model

import HandyJSON
struct UpdateInfo : HandyJSON{

    var updateContent: String?
    var targetVersionNum: String?
    var updateUrl: String?

}
Copy the code

2. Declare the network request function

/// Network request method /// /// -parameter Paramters: parameter // -parameter requestApi: interface Api /// -parameter finished: /// func sendNetworkRequest<T:HandyJSON>(_ paramters: [String: String],requestApi:String,finished:@escaping (_ responseModel: T,_ error: Error?) ->()){ Alamofire.request(BASE_URL, method: .post, parameters: getBaseParamters(paramters, requestCode: requestApi)).responseString { response in if response.result.isSuccess{ if let responseObject = T.deserialize(from: response.result.value) { finished(responseObject,nil) }else{ finished(T(),PXFError.deserialize_Error(response.result.value)) } }else{ finished(T(),response.result.error) } } }Copy the code

3. Initiate a network request

@objc func requestUpdate(){
    var paramters = [String : String]()
    paramters["current_version_num"] = APP_VERSION_CODE
    
    NetworkTool.sharedInstance.sendNetworkRequest(paramters, requestApi: VERSION_UPDATE_API) { (updateInfo:UpdateInfo, error) in
        
        if error == nil{
           ALinLog(error)
        }else{
           ALinLog(updateInfo)
        }
    }
}
Copy the code

4. Implement the Error enumeration type

  public enum PXFError: Error {
      case deserialize_Error(String?)
  }Copy the code