Swift3.0:NSURLConnection的使用

一、介绍

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

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

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

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

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

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

二、示例

同步请求数据方法如下:

//同步请求数据方法如下:
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);
                }
            }
        }
    }

异步请求数据方法如下:

//在控制器声明一个全局的变量,存储解析到的data数据var jsonData:NSMutableData = NSMutableData()
//异步请求数据方法如下:
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);
        }
    }
}

三、解析结果:

(
        {
        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);
        }
    }
}

时间: 2024-08-14 04:57:00

Swift3.0:NSURLConnection的使用的相关文章

(细节控)swift3.0与融云IMKIT开发问题(一部分) override func onSelectedTableRow Method does not override any method from its superclass

原官网文档方案如下,在swift3.0的情况下出现 override func onSelectedTableRow  Method does not override any method from its superclass 这是因为swift3.0 有很多变更,需要更换下onSelectedTableRow参数. //重写RCConversationListViewController的onSelectedTableRow事件 override func onSelectedTableR

Swift2.3 --> Swift3.0 的变化

Swift3.0语法变化 首先和大家分享一下学习新语法的技巧: 用Xcode8打开自己的Swift2.3的项目,选择Edit->Convert->To Current Swift Syntax- 让Xcode帮我们把Swift2.3的代码转换为Swift3.0. 手动调出Xcode自动转换Swift2.3 到 Swift3.0 弹出语言版本选择界面,选择Covert to Swift3,Next:  进入选择模块界面: 选择模块界面 建议只选择自己创建的模块,第三方框架的模块最好不要使用Xco

使用 swift3.0高仿新浪微博

项目地址:https://github.com/SummerHH/swift3.0WeBo 使用 swift3.0 高仿微博,目前以实现的功能有,添加访客视图,用户信息授权,首页数据展示(支持正文中连接匹配,@匹配)支持照片浏览,大图浏览,保存图片到相册本地, 实现发布微博,发微博添加照片,发送Emoticon表情等功能, 先看下项目整体框架 项目使用 MVC 框架,但是在写的过程中也用到了 MVVM设计模式

使用的一些支持swift3.0的开源库

#解决键盘弹起遮挡工具 pod 'IQKeyboardManagerSwift', '~>4.0.6' #多种类型弹出框 pod 'SCLAlertView', :git => 'https://github.com/vikmeup/SCLAlertView-Swift' # Alamofire 网络库 (4.1.0最低支持iOS8.0,4.0最低支持iOS9.0) pod 'Alamofire', '~> 4.0' # swift解析json库 pod 'SwiftyJSON', :g

Swift3.0 函数闭包与OC Block

刚接触Swift,如有不对的点,欢迎指正.转载请说明出处 Swift中定义一个基本函数 //定义一个函数,接收一个字符串,返回一个String类型的值 func test(name:String) -> String { return ("输出了\(name)") } //通用形式 func name(parameters) -> return type { function body } Swift 中基本的闭包函数与OC中Block的相似点 带参闭包 //OC中Bloc

swift3.0:CoreData的使用

一.介绍 CoreData不像slqite3那样编写代码繁琐,同时避免了使用了SQL语句的麻烦,也可以回避使用C语言的语法,降低了iOS开发的技术门槛. CoreData可降低开发成本,提高代码质量.它是一个完全面向对象的API,能够合理管理内存,负责在数据库中存储数据,底层也是由类似 于SQL的技术实现的.CoreData是持久化存储的最佳方式,数据最终的存储类型可以是SQLite数据库.XML.二进制.内存或自定义数据类型 它和SQLite的区别是:只能取出整个实体记录,然后分离,之后才能得

swift3.0 coredata 的使用

//swift3.0在语法上有很大的改变,以简单的增删改查为例,如下: //User类如下: import Foundation import CoreData extension User { @nonobjc public class func fetchRequest() -> NSFetchRequest<User> { return NSFetchRequest<User>(entityName: "User"); } @NSManaged pu

iOS 日期处理 (Swift3.0 NSDate)

处理日期的常见情景 NSDate -> String & String -> NSDate 日期比较 日期计算(基于参考日期 +/- 一定时间) 计算日期间的差异 拆解NSDate对象(分解成year/month/day/hour/minute/second 等) NSDate相关类 NSDate DateFormatter DateComponents DateComponentFormatter Calendar Date structure: Swift3.0中引入了Date s

swift3.0变化总结

Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不仅仅是我下面的这个列表,但是列表中的每一项都是对你的一个巨大的打击. 虽然Swift 3.0 仍处于开发阶段.Swift 3.0 会有很多很多的变化,其中一些可能会在细微之处.然而,我们希望这些变化是一次性的.为了使Swift可以在未来几年更好的发展,在以后的版本更新中改变应该的显著变小.一些Swi

Swift3.0变化分享

Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不仅仅是我下面的这个列表,但是列表中的每一项都是对你的一个巨大的打击. 虽然Swift 3.0 仍处于开发阶段.Swift 3.0 会有很多很多的变化,其中一些可能会在细微之处.然而,我们希望这些变化是一次性的.为了使Swift可以在未来几年更好的发展,在以后的版本更新中改变应该的显著变小.一些Swi