Swift学习笔记(3)iOS 9 中的网络请求
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请求,可以进行以下修改 完整代码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()
}
}
运行结果(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |