• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Swift3.0:NSURLConnection的使用

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、介绍

 应用中也不必不可少的会使用网络通信,增强客户端和服务器的交互,可以使用NSURLConnection实现http通信。

 NSURLConnection提供了异步请求和同步请求两种请求方式。同步请求数据会造成主线程阻塞,通常不建议在请求大数据或者网络不畅时使用。

 不管是同步请求还是异步请求,建立通信的步骤都是一样的:

 1、创建URL对象;
 2、创建URLRequest对象;
 3、创建NSURLConnection连接;

 NSURLConnection创建成功后,就创建了一个http连接。异步请求和同步请求的区别是:

 1、创建了异步请求,用户还可以做其他的操作,请求会在另一个线程执行,通信结果及过程会在回调函数中执行;
 2、创建了同步请求,用户需要在请求结束后才能做其他的操作,这也是通常造成主线程阻塞的原因。

 

二、示例

同步请求数据方法如下:

//同步请求数据方法如下:
func httpSynchronousRequest(){
        
    // 1、创建URL对象;
    let url:URL! = URL(string:"http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10");
        
    // 2、创建Request对象;
    let urlRequest:URLRequest = URLRequest(url:url);
        
    // 3、发起NSURLConnection连接
    NSURLConnection.sendAsynchronousRequest(urlRequest, queue: .main) { (response:URLResponse?, data:Data?, error:Error?) in
            
        if(error != nil){
             print(error?.localizedDescription);
        }else{
             //let jsonStr = String(data: data!, encoding:String.Encoding.utf8);
             //print(jsonStr)
             do {
                 let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
                    print(dic)
                } catch let error{
                    print(error.localizedDescription);
                }
            }
        }
    }

异步请求数据方法如下:

//在控制器声明一个全局的变量,存储解析到的data数据
var
jsonData:NSMutableData = NSMutableData()
//异步请求数据方法如下:
func httpAsynchronousRequest(){
     // 1、创建URL对象;
     let url:URL! = URL(string:"http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10");
        
     // 2、创建Request对象;
     let urlRequest:URLRequest = URLRequest(url:url);
        
     // 3、发起NSURLConnection连接
     let conn:NSURLConnection? = NSURLConnection(request:urlRequest,delegate:self)
     conn?.schedule(in: .current, forMode: .defaultRunLoopMode)
     conn?.start()
}
// MARK - NSURLConnectionDataDelegate
extension ViewController:NSURLConnectionDataDelegate{
    
    func connection(_ connection: NSURLConnection, willSend request: URLRequest, redirectResponse response: URLResponse?) -> URLRequest? {
        
        //发送请求
        return request;
    }
    
    func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
        
        //接收响应
    }
    
    func connection(_ connection: NSURLConnection, didReceive data: Data) {
        
        //收到数据
        self.jsonData.append(data);
    }
    
    func connection(_ connection: NSURLConnection, needNewBodyStream request: URLRequest) -> InputStream? {
        //需要新的内容流
        return request.httpBodyStream;
    }
    
    func connection(_ connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) {
        //发送数据请求
    }
    
    func connection(_ connection: NSURLConnection, willCacheResponse cachedResponse: CachedURLResponse) -> CachedURLResponse? {
        //缓存响应
        return cachedResponse;
    }
    
    func connectionDidFinishLoading(_ connection: NSURLConnection) {
        //请求结束
        //let jsonStr = String(data: self.jsonData as Data, encoding:String.Encoding.utf8);
        //print(jsonStr)
        do {
            let dic = try JSONSerialization.jsonObject(with: self.jsonData as Data, options: JSONSerialization.ReadingOptions.allowFragments)
            print(dic)
        } catch let error{
            print(error.localizedDescription);
        }
    }
}

 

三、解析结果:

(
        {
        currentPage = 1;
        expiredTime = 180000;
        item =         (
                        {
                comments = 134;
                commentsUrl = "http://inews.ifeng.com/ispecial/913/index.shtml";
                commentsall = 1818;
                documentId = "imcp_crc_1063216227";
                id = "http://api.iclient.ifeng.com/TopicApiForCmpp?topicid=913&json=y";
                link =                 {
                    type = topic2;
                    url = "http://api.iclient.ifeng.com/TopicApiForCmpp?topicid=913&json=y";
                    weburl = "http://api.iclient.ifeng.com/TopicApiForCmpp?topicid=913";
                };
                online = 0;
                reftype = editor;
                staticId = "client_special_913";
                style =                 {
                    attribute = "\U4e13\U9898";
                    backreason =                     (
                        "\U5185\U5bb9\U8d28\U91cf\U5dee",
                        "\U65e7\U95fb\U3001\U91cd\U590d",
                        "\U6807\U9898\U515a"
                    );
                    view = titleimg;
                };
                styleType = topic;
                thumbnail = "http://d.ifengimg.com/w198_h141_q100/p3.ifengimg.com/cmpp/2017/04/02/77c9cacd305fbad2554272f27dfc42e2_size39_w168_h120.jpg";
                title = "\U4e60\U8fd1\U5e73\U201c\U4e09\U4f1a\U201d\U5c3c\U5c3c\U65af\U6258";
                type = topic2;
            },
                        {
        ...........
        ...........
        ...........
}    

 

四、源码:

//
//  ViewController.swift
//  NetWorkTest
//
//  Created by 夏远全 on 2017/4/3.
//  Copyright © 2017年 夏远全. All rights reserved.
//

/*
 NSURLConnection的使用:
 
 */

import UIKit

class ViewController: UIViewController {

    var jsonData:NSMutableData = NSMutableData()
    override func viewDidLoad() {
        super.viewDidLoad()
        //httpSynchronousRequest()
        //httpAsynchronousRequest()
    }
    
    //同步请求数据方法如下:
    func httpSynchronousRequest(){
        
        // 1、创建NSURL对象;
        let url:URL! = URL(string:"http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10");
        
        // 2、创建Request对象;
        let urlRequest:URLRequest = URLRequest(url:url);
        
        // 3、发起NSURLConnection连接
        NSURLConnection.sendAsynchronousRequest(urlRequest, queue: .main) { (response:URLResponse?, data:Data?, error:Error?) in
            
            if(error != nil){
                print(error?.localizedDescription);
            }else{
                //let jsonStr = String(data: data!, encoding:String.Encoding.utf8);
                //print(jsonStr)
                do {
                    let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
                    print(dic)
                } catch let error{
                    print(error.localizedDescription);
                }
            }
        }
    }
    
    //异步请求数据方法如下:
    func httpAsynchronousRequest(){
        // 1、创建NSURL对象;
        let url:URL! = URL(string:"http://api.iclient.ifeng.com/ClientNews?id=SYLB10,SYDT10");
        
        // 2、创建Request对象;
        let urlRequest:URLRequest = URLRequest(url:url);
        
        // 3、发起NSURLConnection连接
        let conn:NSURLConnection? = NSURLConnection(request:urlRequest,delegate:self)
        conn?.schedule(in: .current, forMode: .defaultRunLoopMode)
        conn?.start()
    }
}

// MARK - NSURLConnectionDataDelegate
extension ViewController:NSURLConnectionDataDelegate{
    
    func connection(_ connection: NSURLConnection, willSend request: URLRequest, redirectResponse response: URLResponse?) -> URLRequest? {
        
        //发送请求
        return request;
    }
    
    func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
        
        //接收响应
    }
    
    func connection(_ connection: NSURLConnection, didReceive data: Data) {
        
        //收到数据
        self.jsonData.append(data);
    }
    
    func connection(_ connection: NSURLConnection, needNewBodyStream request: URLRequest) -> InputStream? {
        //需要新的内容流
        return request.httpBodyStream;
    }
    
    func connection(_ connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) {
        //发送数据请求
    }
    
    func connection(_ connection: NSURLConnection, willCacheResponse cachedResponse: CachedURLResponse) -> CachedURLResponse? {
        //缓存响应
        return cachedResponse;
    }
    
    func connectionDidFinishLoading(_ connection: NSURLConnection) {
        //请求结束
        //let jsonStr = String(data: self.jsonData as Data, encoding:String.Encoding.utf8);
        //print(jsonStr)
        do {
            let dic = try JSONSerialization.jsonObject(with: self.jsonData as Data, options: JSONSerialization.ReadingOptions.allowFragments)
            print(dic)
        } catch let error{
            print(error.localizedDescription);
        }
    }
}
View Code

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
SWIFT显示底部的工具条发布时间:2022-07-13
下一篇:
swift关于FDFullscreenPopGesture的右滑返回发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap