花落√莫相思

52-Swift 之 NSURLConnection 网络请求

2017-07-27  本文已影响25人  NetWork小贱

一 、 NSURLConnection 的简单介绍

         NSURLConnection 网络请求管理类,在IOS7以后被URLSession 替代。

二 、NSURLConnection: 使用过程中使用到的类

三 、NSURLConnection 的使用步骤

四 、 NSURLConnection 的使用过程中使用到的知识点

1: 网络请求 (CachePolicy) 的缓存情况
2: 网址编码
// TODO : 网址编码
func urlEncoding(urlStr:String?) -> String {
    if urlStr == nil {return urlStr!}
    return urlStr!.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
}
3: JSON 的解析
// TODO : 数据解析

func dataParsing(data:Data) -> Any {
    let dic = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    return dic
}

五、 NSURLConnection 的GET 请求

1> Get 的同步请求

// TODO: NSURLConnection 的Get同步请求数据
func connectionGetSynchronous() -> Void {
    var path = "http://api.3g.ifeng.com/clientShortNews?type=beauty"
    path = self.urlEncoding(urlStr: path)
    /**
     创建URL
     */
    let url = URL.init(string: path)
    /**
     创建请求
     */
    let request = URLRequest.init(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
    /**
     创建响应对象
     */
    var response:URLResponse?
    
    /**
     发起请求
     */
    do {
        let received = try NSURLConnection.sendSynchronousRequest(request, returning: &response)
        /**
         解析数据
         */
        let  dict = try! JSONSerialization.jsonObject(with: received, options: .mutableContainers)
        print(dict)
        /**
         获取响应的头
         */
        let responseHeader = response as! HTTPURLResponse
        print(responseHeader.allHeaderFields)
        
    } catch let error {
        /**
         错误信息打印
         */
        print(error.localizedDescription)
    }
}

** 请求结果的展示 :**

10D1C3B9-EAE8-4E48-9E74-53C68309FE6E.png

2 > Get 的异步请求

// TODO : NSURLConnection 的 GET 的异步请求数据
func connectionGetAsynchronous() -> Void {
    var path = "http://api.3g.ifeng.com/clientShortNews?type=beauty"
    path = self.urlEncoding(urlStr: path)
    /**
     创建URL
     */
    let url = URL.init(string: path)
    /**
     创建请求
     */
    let request = URLRequest.init(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
    /**
     创建请求对象
     */
    let connection = NSURLConnection.init(request: request, delegate: self)
    connection?.schedule(in: .current, forMode: .defaultRunLoopMode)
    connection?.start()
}

NSURLConnectionDataDelegate 的代理方法

// MARK : NSURLConnectionDataDelegate 的代理事件

// TODO : 接受响应
func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
    /**
     接受响应的头
     */
    print(response.expectedContentLength)
    
}

// TODO : 接受数据,请求的数据是一点一点的传过来的
func connection(_ connection: NSURLConnection, didReceive data: Data) {
    loadData.append(data)
}

// TODO : 请求结束
func connectionDidFinishLoading(_ connection: NSURLConnection) {
    let dict = self.dataParsing(data: loadData as Data)
    print(dict)
}

// TODO : 请求失败
func connection(_ connection: NSURLConnection, didFailWithError error: Error) {
     print(error.localizedDescription)
}

func connection(_ connection: NSURLConnection, willSend request: URLRequest, redirectResponse response: URLResponse?) -> URLRequest? {
    /**
     发送请求,在这里可以更改请求头
     */
    var Krequest = request
    Krequest .addValue("", forHTTPHeaderField: "")
    return Krequest
}

请求结果的展示 :

10D1C3B9-EAE8-4E48-9E74-53C68309FE6E.jpeg

六 、 NSURLConnection 的POST 请求

1 > POST 的同步请求

func connectionPostSynchronous() -> Void {
    var path = "http://api.3g.ifeng.com/clientShortNews"
    path = self.urlEncoding(urlStr: path)
    /**
     创建URL
     */
    let url = URL.init(string: path)
    /**
     创建请求
     */
    var request = URLRequest.init(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
    request.httpMethod = "POST"
    /**
     请求的参数
     */
    let param = ["type":"beauty"]
    let paramData = try! JSONSerialization.data(withJSONObject: param, options: .prettyPrinted)
    request.httpBody = paramData
    /**
     创建响应对象
     */
    var response:URLResponse?
    
    /**
     发起请求
     */
    do {
        let received = try NSURLConnection.sendSynchronousRequest(request, returning: &response)
        /**
         解析数据
         */
        let  dict = try! JSONSerialization.jsonObject(with: received, options: .mutableContainers)
        print(dict)
        /**
         获取响应的头
         */
        let responseHeader = response as! HTTPURLResponse
        print(responseHeader.allHeaderFields)
        
    } catch let error {
        /**
         错误信息打印
         */
        print(error.localizedDescription)
    }
}

请求结果的展示 :

F94FA87C-6C2A-49C3-9292-CC9DD7C569C6.jpeg

2> POST的异步请求

// TODO : POST 的异步请求方式
func connectionPostAsynchronous() -> Void {
    var path = "http://api.3g.ifeng.com/clientShortNews"
    path = self.urlEncoding(urlStr: path)
    /**
     创建URL
     */
    let url = URL.init(string: path)
    /**
     创建请求
     */
    var request = URLRequest.init(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
    request.httpMethod = "POST"
    /**
     请求的参数
     */
    let param = ["type":"beauty"]
    let paramData = try! JSONSerialization.data(withJSONObject: param, options: .prettyPrinted)
    request.httpBody = paramData
    /**
     创建请求对象
     */
    let connection = NSURLConnection.init(request: request, delegate: self)
    connection?.schedule(in: .current, forMode: .defaultRunLoopMode)
    connection?.start()
}

注意: POST 的异步请求的代理和 GET 的异步请求代理一样

请求结果的展示 :

355D48F4-1CE5-4B08-80EE-416A2E4E2F35.jpeg

七 、 NSURLConnection 的一些参数

// TODO : NSURLConnection 的参数介绍
func introduceConnection() -> Void {
    var path = "http://api.3g.ifeng.com/clientShortNews?type=beauty"
    path = self.urlEncoding(urlStr: path)
    /**
     创建URL
     */
    let url = URL.init(string: path)
    /**
     创建请求
     */
    let request = URLRequest.init(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)

    let Connection = NSURLConnection.init(request: request, delegate: self)
    
    /**
     获取原始请求
     */
    let originalRequest = Connection?.originalRequest
    print(originalRequest!.url!.absoluteString)
    
    /**
     获取当前请求
     */
    let currentRequest = Connection?.currentRequest
    print(currentRequest!.url!.absoluteString)
    
    #if  true
        /**
         将请求加入指定的RunLoop 中,注意必须保证这时NSURLConnection不能启动,否则不起作用了
         */
        Connection?.schedule(in: .current, forMode: .defaultRunLoopMode)
    #else
        /**
         将请求加入队列中
         */
        let Operation = OperationQueue.init()
        Connection?.setDelegateQueue(Operation)
    #endif
    /**
     取消在 RunLoop 中运行的 Connection ,停止请求
     */
    Connection?.unschedule(from: .current, forMode: .defaultRunLoopMode)
    
    /**
     开始请求
     */
    Connection?.start()
    
    /**
     取消请求
     */
    Connection?.cancel()
}

上一篇下一篇

猜你喜欢

热点阅读