Swift中用NSURLConnection解析URL,并解析Jason数据

使用NSURL的代理方法

用NSMutableData来保存每次获得的数据

@lazy var data = NSMutableData()
用NSJSONNSerialization来解析数据

var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
完整的代码

import UIKit class ViewController: UIViewController, NSURLConnectionDelegate { lazy var data = NSMutableData() override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) 
 let urlPath: String = "http://www.baidu.com" var url: NSURL = NSURL(string: urlPath) var request: NSURLRequest = NSURLRequest(URL: url) var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false) connection.start()
}  
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()        
      }
      func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
         self.data.appendData(data)
        }        
      func connectionDidFinishLoading(connection: NSURLConnection!) {
          var err: NSError        // 如果转换有错误,错误信息保存在err中
          var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: err) as NSDictionary
          println(jsonResult)     
      }
}

你可能感兴趣的:(swift,Jason,NSData,NSURLConnection,nsmutabledata)