加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift学习笔记(3)iOS 9 中的网络请求

发布时间:2020-12-14 06:58:59 所属栏目:百科 来源:网络整理
导读:Swift学习笔记(3)iOS 9 中的网络请求 目录 Swift学习笔记3iOS 9 中的网络请求 目录 编码方法 请求方法 其他修改 完整代码 运行结果 编码方法 在iOS9中,以前常用的stringByAddingPercentEscapesUsingEncoding方法被废除了,取而代之的是stringByAddingPerc

Swift学习笔记(3)iOS 9 中的网络请求

目录

  • Swift学习笔记3iOS 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()
    }

}

运行结果

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读