随着NSURLConnection的弃用,NSURLSession逐渐成为我们使用网络功能的一个常用的基础框架。
由于我们iOS开发中大部分App的网络数据交换是基于HTTP协议的,备注下,Xcode7.0之后,HTTP请求需要做下处理,简单粗暴的方法就是,在info.plist中加入:就好了
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
下面针对NSURLSession的GET
和POST
,进行简单举例。
普通的GET请求
// 获取Url --- 这个是我获取的天气预报接口,时间久了可能就会失效
let url:NSURL = NSURL(string: "http://apis.haoservice.com/weather/city?key=93c921ea8b0348af8e8e7a6a273c41bd")!
// 转换为requset
let requets:NSURLRequest = NSURLRequest(URL: url)
//NSURLSession 对象都由一个 NSURLSessionConfiguration 对象来进行初始化,后者指定了刚才提到的那些策略以及一些用来增强移动设备上性能的新选项
let configuration:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session:NSURLSession = NSURLSession(configuration: configuration)
//NSURLSessionTask负责处理数据的加载以及文件和数据在客户端与服务端之间的上传和下载,NSURLSessionTask 与 NSURLConnection 最大的相似之处在于它也负责数据的加载,最大的不同之处在于所有的 task 共享其创造者 NSURLSession 这一公共委托者(common delegate)
let task:NSURLSessionDataTask = session.dataTaskWithRequest(requets, completionHandler: {
(data:NSData?,response:NSURLResponse?,error:NSError?)->Void in
if error == nil{
do{
let responseData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
/*
error_code = 0
reason = ""
result = 数组套字典的城市列表
*/
print("code:\(responseData["error_code"])")
print("结果: \(responseData["reason"])")
// print("城市列表:\(responseData["result"])")
}catch{
}
}
})
// 启动任务
task.resume()
带头和参数的GET请求
let url:NSURL = NSURL(string: "http://apis.baidu.com/heweather/pro/weather?city=beijing")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "GET"
// 请求的Header
request.addValue("a566eb03378211f7dc9ff15ca78c2d93", forHTTPHeaderField: "apikey")
let configuration:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session:NSURLSession = NSURLSession(configuration: configuration)
let task:NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {
(data:NSData?,response:NSURLResponse?,error:NSError?)->Void in
if error == nil{
do{
let responseData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
print("普通带头与参数的GET请求 --- > \(responseData)")
}catch{
}
}
})
task.resume()
Post的请求
注意内容以HTTPBody的方式传递过去
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
// 这块就是区别啦,其实也差不多
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
(data:NSData?,response:NSURLResponse?,error:NSError?)->Void in
if error == nil{
do{
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Post --- > \(responseString)")
}catch{
print("have catch")
}
}
})
task.resume()
这个测试接口和参数是我不经意看到的,需要翻墙,才能测试成功
假如是带Header的POST请求,我们直接加上request.addValue("value", forHTTPHeaderField: "Key")
,就好了
注意下 HTTPBody我们写入的两种方式
-
直接字典写入
let postDic :NSDictionary = ["id":"13","name":"Jack"] do{ let data:NSData = try NSJSONSerialization.dataWithJSONObject(postDic, options: NSJSONWritingOptions.PrettyPrinted) request.HTTPBody = data }catch{ }
-
JSON字符串转化Data写入
let postString = "id=13&name=Jack" request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
备注参考
http://objccn.io/issue-5-4/
https://github.com/icepy/_posts/issues/10
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/index.html#//apple_ref/occ/cl/NSURLSession