Swift Alamofire
转载:https://www.jianshu.com/p/07b1ec36a689
最近AFNetworking的作者Matt Thompson 提出了一个新的类似AFNetworking的网络基础库,并且专门使用最新的Swift语言写的,名为 Alamofire.
一、正常导入,CocoaPods
1-1、注意下CocoaPods版本
gem install cocoapods
CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+.
-、vim Podfile platform :ios, '8.0'
use_frameworks!
pod 'Alamofire'
//然后 pod install 就OK了
-、导入Alamfire 就可以正常使用了 import Alamofire
注意目前可能会出现这个警告;Cannot load underlying module for 'Alamofire',可以先忽略它,直接 build就没了
二、基本使用
GET请求
普通的get请求
下面是一个天气预报的请求,时间久了,key 会失效
let parameters:Dictionary = ["key":"93c921ea8b0348af8e8e7a6a273c41bd"]
Alamofire.request(.GET, "http://apis.haoservice.com/weather/city", parameters: parameters)
.responseJSON { response in print("result==\(response.result)") // 返回结果,是否成功
if let jsonValue = response.result.value {
/*
error_code = 0
reason = ""
result = 数组套字典的城市列表
*/
print("code: \(jsonValue["error_code"])")
}
}
/*
result==SUCCESS
code: Optional(0)
*/
带head的get请求
let headers = ["apikey":"a566eb03378211f7dc9ff15ca78c2d93"]
Alamofire.request(.GET, "http://apis.baidu.com/heweather/pro/weather?city=beijing", headers: headers)
.responseJSON { response in
print("result==\(response.result)")
if let jsonValue = response.result.value { print("weNeedReuslt == \(jsonValue)")
} }
POST 请求
先看看Alamofire 定义了许多其他的HTTP 方法(HTTP Medthods)可以使用。
public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
使用GET
类型请求的时候,参数会自动拼接在url
后面,使用POST
类型请求的时候,参数是放在在HTTP body
里传递,url
上看不到的
let parameters:Dictionary = ["key":"93c921ea8b0348af8e8e7a6a273c41bd"]
Alamofire.request(.POST, "http://apis.haoservice.com/weather/city", parameters: parameters)
.responseJSON { response in print("result==\(response.result)") // 返回结果,是否成功
if let jsonValue = response.result.value {
/*
error_code = 0
reason = ""
result = 数组套字典的城市列表
*/
print("code: \(jsonValue)")
}
}
至于加header的post 请求,实际上也是GET 一样的
注意点1: 参数编码方式
除了默认的方式外,Alamofire还支持URL、URLEncodedInURL、JSON、Property List以及自定义格式方式编码参数。
public enum ParameterEncoding {
case URL
case URLEncodedInURL
case JSON
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
}
//想要把一个字典类型的数据,使用json格式发起POST请求
let parameters = [
"one": [,,],
"two": ["apple": "pig"]
] Alamofire.request(.POST, "http://www.example.com/service", parameters: parameters, encoding: .JSON)
注意点2:validate()
将其与请求和响应链接,以确认响应的状态码在默认可接受的范围(200到299)内。如果认证失败,响应处理方法将出现一个相关错误,我们可以根据不同在完成处理方法中处理这个错误。比如下面的样例,成功时会打印成功信息,失败时输出具体错误信息。
Alamofire.request(.GET, "http://apis.haoservice.com/weather/city", parameters: ["apikey":"a566eb03378211f7dc9ff15ca78c2d93"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
print("数据获取成功!")
case .Failure(let error):
print(error)
}
}
注意点3:响应处理方法
观察上面几个请求,我都是使用样例的responseJSON(处理json类型的返回结果)外,Alamofire还提供了许多其他类型的响应处理方法:
response()
responseData()
responseString(encoding: NSStringEncoding)
responseJSON(options: NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)
我们可以根据我的实际情况,选择自己需要的。
例如 responseData()
Alamofire.request(.GET, "http://apis.haoservice.com/weather/city", parameters: ["apikey":"a566eb03378211f7dc9ff15ca78c2d93"])
.responseData { response in
print(response.request)
print(response.response)
print(response.result)
}
暂时基本使用,总结到此,持续更新中····️
备注参考
https://github.com/Alamofire/Alamofire
http://www.hangge.com/blog/cache/detail_970.html
http://www.cnblogs.com/iCocos/p/4550570.html
Swift Alamofire的更多相关文章
- swift Alamofire请求数据与SwiftJson解析
一直在研究swift 程序最重要的是什么???答案当然是数据啦. 数据对一个程序的影响有多大自己想去吧!!!如果你非要说不重要,那你现在就可以关网页了 哈哈哈哈哈 我呢 swift新手 菜鸟一 ...
- Swift: Alamofire -> http请求 & ObjectMapper -> 解析JSON
1 2 3 4 5 6 7 8 9 10 11 NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.js ...
- [Swift]Alamofire:设置网络请求超时时间【timeout】的两种方式
两种方式作用相同,是同一套代码的两种表述. 第一种方式:集聚. 直接设置成员属性(全局属性),这种方法不能灵活修改网络请求超时时间timeout. 声明为成员属性: // MARK: - 设置为全局变 ...
- iOS开发——网络编程Swift篇&Alamofire详解
Alamofire详解 预览图 Swift Alamofire 简介 Alamofire是 Swift 语言的 HTTP 网络开发工具包,相当于Swift实现AFNetworking版本. 当然,AF ...
- iOS - Alamofire 网络请求
前言 Alamofire 是 Swift 语言的 HTTP 网络开发工具包,相当于 Swift 实现 AFNetworking 版本.当然,AFNetworking 非常稳定,在 Mac OSX 与 ...
- IOS 开发教程
http://www.raywenderlich.com/category/ios http://www.raywenderlich.com/50310/storyboards-tutorial-in ...
- iOS的非常全的三方库,插件,大牛博客
转自: http://www.cnblogs.com/zyjzyj/p/6015625.html github排名:https://github.com/trending, github搜索:http ...
- ios优秀的第三方框架
1.数据请求,object-c AFNetworking 网址:https://github.com/AFNetworking/AFNetworking swift Alamofire 网址:h ...
- ios很好的开源库
Tim9Liu9/TimLiu-iOS 自己总结的iOS.mac开源项目及库,持续更新.. 目录 UI 下拉刷新 模糊效果 AutoLayout 富文本 图表 表相关与Tabbar 隐藏与显示 HUD ...
随机推荐
- keepalived 热备
概述 keepalived高可用集群 keepalived最初是为了LVS的,因为LVS无法进行自动检测服务器的节点状态(可以自动部署LVS) keeplived后来加入VRRP给功 ...
- Re5ilio 5ync:资源神器
文章目录 #0x0 简单的介绍 #0x1 安装使用 #0x10 下载 #0x11 安装 #0x12 升级pro权限 #0x13 开始添加资源 #0x14 后续 一定要小心哦!! #0x0 简单的介绍 ...
- vue中v-model父子组件通信
有这样的需求,父组件绑定v-model,子组件输入更改父组件v-model绑定的数值.是怎么实现的呢? 实际上v-model 只是语法糖而已. <input v-model="inpu ...
- DVWA学习记录 PartⅤ
File Upload 1. 题目 File Upload,即文件上传漏洞,通常是由于对上传文件的类型.内容没有进行严格的过滤.检查,使得攻击者可以通过上传木马获取服务器的webshell权限,因此文 ...
- Java实现 LeetCode第30场双周赛 (题号5177,5445,5446,5447)
这套题不算难,但是因为是昨天晚上太晚了,好久没有大晚上写过代码了,有点不适应,今天上午一看还是挺简单的 5177. 转变日期格式 给你一个字符串 date ,它的格式为 Day Month Yea ...
- db2数据库字段更新当前时间
db2数据库中想要将字段的时间通过sql语句的方式更新: 例如: Update tablename set 字段1='打酱油', 字段2 = TO_CHAR(current timestamp,'YY ...
- OSCP Learning Notes - Netcat
Introduction to Netcat Connecting va Listening Bind Shells Attacker connects to victim on listening ...
- OSCP Learning Notes - Buffer Overflows(4)
Finding the Right Module(mona) Mona Module Project website: https://github.com/corelan/mona 1. Downl ...
- Python Ethical Hacking - Packet Sniffer(2)
Capturing passwords from any computer connected to the same network. ARP_SPOOF + PACKET_SNIFFER Ta ...
- 少儿编程:python趣味编程第一课
本文仅针对8-16岁的青少年,所以流程是按如何去教好中小学生走的,并不适合成人找工作学习,因为进度也是按照青少年走的 大家好,我是C大叔,从事少儿编程行业三年有余(2016年从事少儿编程行业,少儿编程 ...