分享

[快速学会Swift第三方库]AlamofireObjectMapper

 昵称v8JFa 2016-10-12

[快速学会Swift第三方库]AlamofireObjectMapper篇

通常网络请求返回的是JSON数据,使用ObjectMapper可以让JSON数据直接转化为对象,而使用Alamofire进行网络请求时,使用AlamofireObjectMapper可以直接返回对象,更加简洁。
Alamofire的使用:[快速学会Swift第三方库] Alamofire篇
ObjectMapper在非Alamofire请求下的使用:GitHub-ObjectMapper主页

目录

编码之前

导入AlamofireObjectMapper

推荐使用CocoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻松地对所有第三方开源库进行安装和更新,而不需要每次上GitHub去下载。
CocoaPods的安装过程传送门:iOS 9 导入类库全面详尽过程(Ruby安装->CocoaPods安装->导入类库)
手动下载:GitHub-AlamofireObjectMapper 主页

装好CocoaPods后,修改Podfile文件内容为如下:

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'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

target后面为工程名,最后一行为工程路径(这里的Web是我的工程名)

再执行命令:

$ pod install
  • 1

注意:会自动导入ObjectMapper

其他操作

另外还需要在Target->工程名->Build Settings->Search Paths->User Header Search Paths处添加AlamofireObjectMapper所在的目录:

这里写图片描述

最后在你需要用到AlamofireObjectMapper的类中加上:

import AlamofireObjectMapper
  • 1

创建 Mappable 对象

这里采用的Alamofire的测试接口 https:///get

在浏览器中打开可以看到JSON格式的数据:

{
  "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": "", 
    "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:///get"
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

根据该JSON的数据格式创建以下两个Mapper类分别对应整个字典和key值为“header”的字典。将JSON中的数据与对象中的数据一一建立转化关系。

import Foundation
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"]
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
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"]
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

用Alamofire获取对象

    func webRequst()  {
        let url = "https:///get"
        //注意返回的类型为<Mappable对象,NSError>
        Alamofire.request(.GET, url).responseObject { (response: Response<MyResponse, NSError>) in
            let myResponse = response.result.value
            print(myResponse?.url)
            if let header = myResponse?.headers{
                print(header.userAgent)
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

返回的Mappable对象可以直接使用,运行结果:

Optional("https:///get")
Optional("Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))")
  • 1
  • 2

深入学习

如果你想更多地了解AlamofireObjectMapper,可以前往GitHub-ObjectMapper主页

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多