標籤:
前言:移動互連網時代,網路通訊已經是手機端必不可少的功能。應用中也必不可少地使用了網路通訊,增強用戶端與伺服器互動。使用NSURLConnection實現HTTP的通訊。NSURLConnection 提供了非同步請求和同步請求兩種通訊方式。同步請求資料會造成主線程阻塞,通常在請求大資料或網路不通暢時不建議使用。
不管同步請求還是非同步請求,建立通訊的步驟是一樣的:
1 建立NSURL
2 建立NSURLRequest
3 建立NSURLConnection
當NSURLConnection 建立成功後,就會建立一個HTTP串連。非同步請求和同步請求的區別是:建立了非同步請求,使用者可以做其他的操作,請求會再另一個線程執行,通訊結果及過程會在回呼函數中執行。同步請求則不同,需要請求結束使用者才能做其他的操作。
import UIKitclass 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. }}
IOS SWIFT 網路請求JSON解析 基礎一