IOS SWIFT 网络请求JSON解析 基础一

前言:移动互联网时代,网络通信已经是手机端必不可少的功能。应用中也必不可少地使用了网络通信,增强客户端与服务器交互。使用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.

        
    }


}

 

原文地址:https://www.cnblogs.com/itboyblog/p/4781031.html