您的位置:首页 > 理论基础 > 计算机网络

网络通信

2015-11-20 16:00 288 查看
用字符串来加载网页的html信息

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
var str = String()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//用字符串来加载网页的html信息
do {  str = try NSString(contentsOfURL:NSURL(string: "http://jikexueyuan.com")!, encoding: NSUTF8StringEncoding) as String
}
catch {
print("加载失误")
}
print(str)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}


读成二进制的文件

import UIKit

class ViewController: UIViewController {
var data = NSData()
override func viewDidLoad() {

super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//加载成二进制的数据
data = ((NSData(contentsOfURL: ((NSURL(string: "http://www.baidu.com")))!)!))
print(data)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


不过这样做一直会线程崩溃

以上这两种方式都是同步的,也就是主界面的UI是处于卡死状态的,用户是不能操作的,所以,这两种方法在操作本地的文件时,是可以用得,在操作网络数据时,不建议

import UIKit

class ViewController: UIViewController {
var data = NSData()
override func viewDidLoad() {

super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//用同步加载 send来加载网络上得数据,先不回应得到数据后的应答

do { var data = try NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: NSURL(string: "http://www.baidu.com")!), returningResponse: nil)
}
catch {
print("error")
}
//转化成字符串类型输出 原先是二进制的类型
print(NSString(data: data, encoding: NSUTF8StringEncoding))

}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}


应答头是http协议的数据

所以先定义

var resp:NSURLResponse?


再将其地址传入

do { var data = try NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: NSURL(string: "http://www.baidu.com")!), returningResponse: &resp)


实质上错误已经在抛出异常时处理了

异步的处理,实质上是为了防止主界面线程UI的占用

import UIKit
import SystemConfiguration
class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//异步请求数据,是为了不影响用户的主界面。来下载数据 不能够影响主队列
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "http://www.baidu.com")!), queue: NSOperationQueue()) { (resp:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
if let e = error {
print("发生错误")
}else {
print(NSString(data: data! , encoding: NSUTF8StringEncoding))
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: