Swift学习笔记(3)iOS 9 中的网络请求
目录
编码方法
在iOS9中,以前常用的stringByAddingPercentEscapesUsingEncoding方法被废除了,取而代之的是stringByAddingPercentEncodingWithAllowedCharacters方法。
用法示例:
var strURL=String(format:"http://blog.csdn.net/sps900608")
//等价于strURL=strURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
strURL=strURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString:"`#%^{}\"[]|\\<> ").invertedSet)!
此外还可以如下写法:
strURL=strURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet)!
NSCharacterSet常用的类型有以下:
URLHostAllowedCharacterSet "#%/<>?@\^`{|} URLFragmentAllowedCharacterSet "#%<>[\]^`{|} URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|} URLPathAllowedCharacterSet "#%;<>?[\]^`{|} URLQueryAllowedCharacterSet "#%<>[\]^`{|} URLUserAllowedCharacterSet "#%/:<>?@[\]^`
请求方法
在iOS 9中NSURLConnection类被废除,替代者是NSURLSession类
使用示例:
let session=NSURLSession.sharedSession()
let dataTask=session.dataTaskWithRequest(request) { (data,reponse,error) -> Void in
if (error != nil){
NSLog("Error:\(error?.localizedDescription)")
}
else{
self.webView.loadData(data!,MIMEType: "text/html",textEncodingName: "utf-8",baseURL: url)
}
}
dataTask.resume()
NSURLsessionTask共有3个实体子类,应用于3种不同的场景,分别是NSURLSessionDataTask(数据请求)、NSURLSessionUploadTask(上传)、NSURLSessionDownloadTask(下载),上述代码使用的是NSURLSessionDataTask(数据请求)。
其他修改
在iOS 9中,进行HTTP请求会报以下错误“Transport Security policy requires the use of a secure connection”,苹果官方推荐使用安全性更好的HTTPS协议,如果仍要进行HTTP请求,可以进行以下修改
选择info.plist,在Info.plist中添加App Transport Security Settings类型Dictionary。然后在App Transport Security Settings下添加Allow Arbitrary Loads类型Boolean,值设为YES。如下图所示:
完整代码
import UIKit
class ViewController: UIViewController {
@IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
startRequest()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startRequest(){
var strURL=String(format:"http://blog.csdn.net/sps900608")
strURL=strURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString:"`#%^{}\"[]|\\<> ").invertedSet)!
let url=NSURL(string: strURL)!
let request=NSURLRequest(URL: url)
let session=NSURLSession.sharedSession()
let dataTask=session.dataTaskWithRequest(request) { (data,error) -> Void in
if (error != nil){
NSLog("Error:\(error?.localizedDescription)")
}
else{
self.webView.loadData(data!,MIMEType: "text/html",textEncodingName: "utf-8",baseURL:url)
}
}
dataTask.resume()
}
}