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 ...
随机推荐
- 钉钉内置的浏览器怎么改变title
在我项目的开发过程当中,遇到过在钉钉打开的vue写的h5页面,通过在路由切换的时候通过全局的路由钩子函数改变 document.title 的内容失效的问题. const routes = [ { p ...
- Docker装的Oracle 11g没有HR用户怎么办?一个脚本解决问题!
#0x0 问题描述 这个学期有一门Oracle的课,我图省事就直接拉了个docker镜像来做练习,一直倒也没啥问题,但是今天的作业需要用到HR这个模板用户. 然而我执行alter user hr ac ...
- python 并发专题(四):yield以及 yield from
一.yield python中yield的用法很像return,都是提供一个返回值,但是yield和return的最大区别在于,return一旦返回,则代码段执行结束,但是yield在返回值以后,会交 ...
- Quartz.Net系列(十三):DateBuilder中的API详解
1.DateOf.ToDayAt.TomorrowAt DateOf:指定年月日时分秒 public static DateTimeOffset DateOf(int hour, int minute ...
- 并发编程之synchronized(二)------jvm对synchronized的优化
一.锁的粗化 看如下代码 public class Test { StringBuffer stb = new StringBuffer(); public void test1(){ //jvm的优 ...
- CocosCreator之AssetBundle使用方案分享
前言 Creator2.4 推出了AssetBundle,使得所有平台都有了分包的能力.那么该如何使用这个强大的功能呢?下面介绍一下我个人的用法,仅供参考,水平有限,非喜勿喷. 根据官方文档 指出,之 ...
- OSCP Learning Notes - Exploit(7)
Pre-Exploit Password Attacks Tools: 1. ncrack Ncrack 0.6 ( http://ncrack.org )Usage: ncrack [Options ...
- javascript实战 : 简单的颜色渐变
HTML <div id="color"></div> CSS .item{ display:inline-block; margin:10px; widt ...
- HashTable、HashMap与ConCurrentHashMap源码解读
HashMap 的数据结构 hashMap 初始的数据结构如下图所示,内部维护一个数组,然后数组上维护一个单链表,有个形象的比喻就是想挂钩一样,数组脚标一样的,一个一个的节点往下挂. 我们可以 ...
- 02 安装net-tools工具
01 登录虚拟机,没错,还是那个熟悉的黑窗口 02 输入用户名密码(我还是习惯使用root用户,因为,它可以为所欲为) 小知识:注意红色框内的符号: 一般用户为限制用户,符号为:$ 超级用户,为无限制 ...