AlamofireObjectMapper

        平日网络请求再次来到的是JSON数据,使用ObjectMapper能够让JSON数据直接转账为目标,而采用Alamofire进行网络请求时,使用AlamofireObjectMapper能够直接回到对象,特别简明。

Alamofire :https://github.com/Alamofire/Alamofire

Podfile文件内容为如下:

先引用 import  Alamofire

source’https://github.com/CocoaPods/Specs.git

platform:ios,’9.0′

use_frameworks!

target’Web’do

pod’AlamofireObjectMapper’,’~> 3.0′

end

xcodeproj’Desktop/Web/Web.xcodeproj’

供给互连网请求时利用上边那段

target前边为工程名,最终1行为工程路径(那里的Web是我的工程名)

Alamofire.request(“https://api.500px.com/v1/photos“, method:
.get).responseJSON {  response in 

外加操作:

guardletJSON= response.result.valueelse{return}

Target->工程名->Build Settings->Search Paths->User Header
Search Paths处增多AlamofireObjectMapper所在的目录:

print(“JSON:\(JSON)”)

末段在您需求用到AlamofireObjectMapper的类中增进:

}

importAlamofireObjectMapper

一般大家须要在等级次序中封装一下 Alamofire 在运用 


类型相应有1个类进行网络请求 ,上边正是三个post请求的包装

创建 Mappable 对象

{

“args”:{},

“headers”:{    

“Accept”:”text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8″, 
  

“Accept-Encoding”:”gzip, deflate, br”,

 “Accept-Language”:”zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3″, 

 “Cache-Control”:”max-age=0″,    

 “Host”:”httpbin.org”,    

 “User-Agent”:”Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0)
Gecko/20100101 Firefox/46.0″

},

“origin”:”202.115.52.218″,

“url”:”https://httpbin.org/get

}

       
 根据该JSON的多寡格式创设以下多个Mapper类分别对应总体字典和key值为“header”的字典。将JSON中的数据与对象中的数据壹第1建工公司立转化关系。
 

import ObjectMapper

class ResponseHeader: Mappable {

var accept : String?

var acceptEncoding : String?

var acceptLanguage : String?

var cacheControl : String?

var host : String?

var userAgent : String?

required init?(_ map: Map) {

}

//映射heades字典中的全部键值

func mapping(map: Map) {

accept <- map[“Accept”]

acceptEncoding <- map[“Accept-Encoding”]

acceptLanguage <- map[“Accept-Language”]

cacheControl <- map[“Cache-Control”]

host <- map[“Host”]

userAgent <- map[“User-Agent”]

}

}

import Foundation

import ObjectMapper

class MyResponse: Mappable {

var args : NSDictionary?

var headers : ResponseHeader?

var origin : String?

var url : String?

required init?(_ map: Map) {

}

//映射字典中的全部键值

func mapping(map: Map) {

args <- map[“args”]

headers <- map[“headers”]

origin <- map[“origin”]

url <- map[“url”]

}

}

class func PostSendData(dic:[String: String], url:String,
successed:@escaping (_ responseObject: AnyObject?) -> (), failed:
@escaping (_ error: NSError?) -> ())  {

用Alamofire获取对象

webRequst() { let url = “https://httpbin.org/get
//注意重临的门类为Alamofire.request(.GET, url).responseObject {
(response: Response) in

let myResponse = response.result.value

print(myResponse?.url)

if let header = myResponse?.headers{

print(header.userAgent)

}

}

}

打字与印刷内容:

Optional(“https://httpbin.org/get“)

Optional(“Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))”)

Alamofire的使用:[高速学会Swift第贰方库]
Alamofire篇

ObjectMapper在非Alamofire请求下的行使:GitHub-ObjectMapper主页

Alamofire.request(url, method: .post, parameters: dic).responseJSON {
(returnResult) in

switch returnResult.result {

      case .success:

           // 解析json

             let JSON = returnResult.result.value as? NSDictionary

            successed(JSON)

          break

    case .failure(_):

         failed(returnResult.result.error! as NSError)

       break

   }

}

ObjectMapper的使用

建3个类 承接与NSObject  遵从Mappable  

引用 import ObjectMapper

例:class MainDataModel:NSObject ,Mappable{

    var docid: String?

    var touxiang: String?

    var lastcontent: String?

    var time: String?

    required init?(map: Map){

   }

func mapping(map: Map) {

    docid              <- map[“docid”]

    touxiang            <- map[“touxiang”]

    lastcontent        <- map[“lastcontent”]

    time                <- map[“time”]

  }

}

用刚刚方面封装的post请求请求数据

NetWorkingRequestCenter.PostSendData(dic: dic, url: “xxxxxxx”,
successed: { (response) in                                   
print(response )                       

    let arr = response?[“doinglist”] as! NSArray                     
 

     var backArray = [MainDataModel]()                      

     for i in 0…arr.count-1{                               

         let att = arr[i]                               

        let model = Mapper.init().map(JSON: att as! [String : Any])

       print(model?.docid ?? “aa”)

       backArray.append(model!)

   }

}) { (error) in

print(error?.code ?? “failure”)

}

图片 1

Leave a Comment.