前言:移动互联网时代,网络通信已经是手机端必不可少的功能。应用中也必不可少地使用了网络通信,增强客户端与服务器交互。使用NSURLConnection实现HTTP的通信。NSURLConnection 提供了异步请求和同步请求两种通信方式。同步请求数据会造成主线程阻塞,通常在请求大数据或网络不通畅时不建议使用。

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

1 创建NSURL

2 创建NSURLRequest

3 创建NSURLConnection

当NSURLConnection 创建成功后,就会创建一个HTTP连接。异步请求和同步请求的区别是:创建了异步请求,用户可以做其他的操作,请求会再另一个线程执行,通信结果及过程会在回调函数中执行。同步请求则不同,需要请求结束用户才能做其他的操作。

import UIKit

class ViewController: UIViewController,NSURLConnectionDataDelegate {

    var jsonData = NSMutableData()

    override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib. //SynchronousRequest()
//AsynchronousRequest()
} //同步请求
func SynchronousRequest() -> Void {
//创建需要求的NSURL
var url : NSURL! = NSURL(string: "http://m.weather.com.cn/mweather/101010100.html")
//创建请求对象
var request = NSURLRequest(URL: url)
//定义响应对象
var response : NSURLResponse?
//定义错误对象
var error : NSError?
//发出请求
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) if (error != nil) {
//处理错误
println(error?.code)
println(error?.description)
} else {
var josnstring = NSString(data: data!, encoding: NSUTF8StringEncoding)
//转为字符串
println(josnstring)
} } //异步请求
func AsynchronousRequest() -> Void {
//创建需要求的NSURL
var url : NSURL! = NSURL(string: "http://m.weather.com.cn/mweather/101010100.html")
//创建请求对象
var request = NSURLRequest(URL: url)
//创建连接
var connection = NSURLConnection(request: request, delegate: self)
//暂时理解不透彻,待深入了解
connection?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
//开始
connection?.start()
} //将要发送请求
func connection(connection: NSURLConnection, willSendRequest request: NSURLRequest, redirectResponse response: NSURLResponse?) -> NSURLRequest? {
return request
} //接收响应
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { } //收到数据
func connection(connection: NSURLConnection, didReceiveData data: NSData) {
self.jsonData.appendData(data)
} //需要新的内容流
func connection(connection: NSURLConnection, needNewBodyStream request: NSURLRequest) -> NSInputStream? {
return request.HTTPBodyStream
} //发送数据请求
func connection(connection: NSURLConnection, didSendBodyData bytesWritten: Int, totalBytesWritten: Int, totalBytesExpectedToWrite: Int) { } //缓存响应
func connection(connection: NSURLConnection, willCacheResponse cachedResponse: NSCachedURLResponse) -> NSCachedURLResponse? {
return cachedResponse
} //请求结束
func connectionDidFinishLoading(connection: NSURLConnection) {
//请求的结果
var jsonstring = NSString(data: self.jsonData, encoding: NSUTF8StringEncoding) //转为字符串 //println(jsonstring) //解析json
let dict : AnyObject? = NSJSONSerialization.JSONObjectWithData(self.jsonData, options: NSJSONReadingOptions.AllowFragments, error: nil) var dic = dict as! NSDictionary let weatherinfo = dic.objectForKey("weatherinfo") as! NSDictionary
let city = weatherinfo.objectForKey("city") as! String
let date_y = weatherinfo.objectForKey("date_y") as! String
let temp1 = weatherinfo.objectForKey("temp1") as! String } override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated. } }

最新文章

  1. 代码提交的时候可以插入表情了-GitHub表情的使用
  2. 让网站动起来!12款优秀的 jQuery 动画插件推荐
  3. c++的构造函数
  4. 进程和线程及Linux下的编程
  5. JS/PHP 浮点数精确运算
  6. UVa 437 The Tower of Babylon(经典动态规划)
  7. CA*Layer(CAShapeLayer--CATextLayer)
  8. MySQL(17):Select-union(联合查询)使用注意事项
  9. 第一章 Windows NT System Components
  10. 手把手教你使用python复杂一点点的装饰器
  11. 【深搜加剪枝】【HDU1455】【Sticks】
  12. MySQL的联结(Join)语法
  13. CRM Entity 之Money转string int类型等
  14. 对BRD、MRD、PRD、FSD四类产品文档的理解
  15. Go语言数组
  16. ubuntu下搭建svn服务器
  17. [转]GDB-----1.GDB概述
  18. 强化学习---A3C
  19. SAS DATA ENCODING 解决odbc乱码问题
  20. 锐浪报表 导出 PDF ANSI码 乱码 问题解决

热门文章

  1. 设计模式 - 适配器模式(adapter pattern) 具体解释
  2. GDB学习之道:GDB调试精粹及使用实例
  3. Objective-c 类实现 (@implementation)
  4. 去除List列表中反复值(稍作调整,也适合于List<T> 和 List<?>)
  5. js中的setTimeout和setInterval
  6. centos6.5配置163的yum源
  7. D1-Linux-CentOS学习打卡
  8. Kqueue与epoll机制
  9. 深入浅出—JAVA(6)
  10. LinuxC安装gcc