標籤:style blog http color io os 使用 ar for
//// ViewController.swift// http_request//// Created by andy on 14-9-6.// Copyright (c) 2014年 andy. All rights reserved.//import UIKitclass ViewController: UIViewController { @IBOutlet var btn:UIButton? @IBOutlet var lable:UILabel? override func viewDidLoad() { super.viewDidLoad() //TextField } @IBAction func btnClick(AnyObject) { // ss() loadJsonData() } //解析JSON的方法 func loadJsonData(){ //定義擷取json資料的介面地址,這裡定義的是擷取天氣的API介面,還有一個好處,就是swift語句可以不用強制在每條語句結束的時候用";" var url = NSURL(string:"http://www.weather.com.cn/data/sk/101110101.html") //擷取JSON資料 var data = NSData.dataWithContentsOfURL(url,options:NSDataReadingOptions.DataReadingUncached,error:nil) var json:AnyObject = NSJSONSerialization.JSONObjectWithData(data,options:NSJSONReadingOptions.AllowFragments,error:nil)! //解析擷取JSON欄位值 var weatherInfo:AnyObject = json.objectForKey("weatherinfo")! //json結構欄位名。 var city:AnyObject = weatherInfo.objectForKey("city")! //以此類推擷取其他欄位的資訊,再此我就不過多贅述了。 //然後把擷取到的json值賦值個相應的控制項即可。 //tv.text = "城市:\(city)" //使用\()可以將變數嵌入到相應的字串中, println(city) } func ss() { let urlPath: String = "http://www.weather.com.cn/data/sk/101010100.html" var url: NSURL = NSURL(string: urlPath) var request1: NSURLRequest = NSURLRequest(URL: url) let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in /* Your code */ var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary println("AsSynchronous\(jsonResult)") }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}
ios swift http json