Swift学习笔记(3)iOS 9 中的网络请求
目录
编码方法
在iOS9中,以前常用的stringByAddingPercentEscapesUsingEncoding方法被废除了,取而代之的是stringByAddingPercentEncodingWithAllowedCharacters方法。
用法示例:
@H_502_31@var strURL=String(format:"http://blog.csdn.net/sps900608") //等价于strURL=strURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) strURL=strURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString:"`#%^{}\"[]|\\<> ").invertedSet)!此外还可以如下写法:
@H_502_31@strURL=strURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet)!NSCharacterSet常用的类型有以下:
URLHostAllowedCharacterSet "#%/<>?@\^`{|} URLFragmentAllowedCharacterSet "#%<>[\]^`{|} URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|} URLPathAllowedCharacterSet "#%;<>?[\]^`{|} URLQueryAllowedCharacterSet "#%<>[\]^`{|} URLUserAllowedCharacterSet "#%/:<>?@[\]^`
请求方法
在iOS 9中NSURLConnection类被废除,替代者是NSURLSession类
使用示例:
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。如下图所示: