一、介绍

应用中也不必不可少的会使用网络通信,增强客户端和服务器的交互,可以使用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);
}
}
}

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

  1. Swift3.0服务端开发(一) 完整示例概述及Perfect环境搭建与配置(服务端+iOS端)

    本篇博客算是一个开头,接下来会持续更新使用Swift3.0开发服务端相关的博客.当然,我们使用目前使用Swift开发服务端较为成熟的框架Perfect来实现.Perfect框架是加拿大一个创业团队开发 ...

  2. 算法与数据结构(十三) 冒泡排序、插入排序、希尔排序、选择排序(Swift3.0版)

    本篇博客中的代码实现依然采用Swift3.0来实现.在前几篇博客连续的介绍了关于查找的相关内容, 大约包括线性数据结构的顺序查找.折半查找.插值查找.Fibonacci查找,还包括数结构的二叉排序树以 ...

  3. Swift3.0变化分享

    Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不 ...

  4. swift3.0变化总结

    Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不 ...

  5. 关于for循环------swift3.0

    在程序开发当中,for循环使用的频率无疑是最高的.常用的swift循环是递增式遍历.当然各种循环,swift都能办到.但其大多采用关键字形式实现,大部分开发者更喜欢直接使用C式循环代码.在swift3 ...

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

    Swift3.0语法变化 首先和大家分享一下学习新语法的技巧: 用Xcode8打开自己的Swift2.3的项目,选择Edit->Convert->To Current Swift Synt ...

  7. Swift3.0都有哪些变化

    从写第一篇Swift文章的时候到现在Swift已经从1.2发展到了今天的3.0,这期间由于Swift目前还在发展阶段并不能向下兼容,因此第一篇文章中的部分代码在当前的Xcode环境中已经无法运行.在W ...

  8. iOS开发 swift3.0中文版

    swift3.0中文版: http://pan.baidu.com/s/1nuHqrBb

  9. swift3.0的改变

    Swift在这2年的时间内,发展势头迅猛,在它开源后,更是如井喷一样,除了 iOS.mac 平台,还支持了 Linux. 而今年下半年, Swift 3.0 也会随之发布.https://github ...

  10. Swift3.0语言教程字符串与URL的数据转换与自由转换

    Swift3.0语言教程字符串与URL的数据转换与自由转换 Swift3.0语言教程字符串与URL的数据转换 Swift3.0语言教程字符串与URL的数据转换与自由转换,字符串中的字符永久保存除了可以 ...

随机推荐

  1. 利用HTML5定位功能,实现在百度地图上定位(转)

    原文:利用HTML5定位功能,实现在百度地图上定位 代码如下: 测试浏览器:ie11定位成功率100%,Safari定位成功率97%,(add by zhj :在手机上测试(用微信内置浏览器打开),无 ...

  2. 001.VNC介绍

    一 VNC介绍 VNC 服务是一个自由开源软件,采用RFB通信协议.RFB ("remote 帧缓存 ") 是一个远程图形用户的简单协议,因为它工作在帧缓存级别上,所以它可以应用于 ...

  3. 004.FTP匿名用户访问

    一 匿名用户配置项 [root@imxhy~]# vi /etc/vsftpd/vsftpd.conf anonymous_enable #允许匿名用户访问 anon_upload_enable #允 ...

  4. 多线程十之CopyOnWriteArrayList源码分析

    目录 简介 类结构 源码解析 构造方法 add(E e) add(int index, E element) get(int index) remove(int index) 迭代器Iterator遍 ...

  5. 【WIN10】Segoe MDL2 Assets

    APP下載地址:https://www.microsoft.com/store/apps/9nblggh5k2hf 最近使用文本圖標Segoe MDL2 Assets時,使用字符映射表看,那個圖標真的 ...

  6. codevs 3185 队列练习 1

    时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold       题目描述 Description 给定一个队列(初始为空),只有两种操作入队和出队,现给出这些操作请输出最 ...

  7. 自动化运维_Ansible

    1. 前言 Ansible是自动化运维的工具,基于Python开发,实现了批量系统配置.批量程序部署.批量运行命令等功能. Ansible是基于模块工作的,ansible提供一个框架,通过模块实现批量 ...

  8. HDU 4758 Walk Through Squares (2013南京网络赛1011题,AC自动机+DP)

    Walk Through Squares Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Oth ...

  9. python脚本从excel表到处数据,生成指定格式的文件

    #coding:gbk #导入处理excel的模块 import xlrd #定义哪些字段须要推断,仅仅支持时间字段 toSureColArray = ['CREATE_TIME','MODIFY_T ...

  10. Delphi取UTC时间秒

    自格林威治标准时间1970年1月1日00:00:00 至现在经过多少秒数时间模块Uses   DateUtils;当前时间:中国是 +8时区,换成UTC 就要减掉8小时showMessage(intt ...