2015-07-12 67 views
-2

所以我得從Wunderground天氣API文檔此示例代碼:http://www.wunderground.com/weather/api/d/docs?d=resources/code-samples&MR=1解析GET請求與斯威夫特

我怎樣才能獲得相同的信息(在這種情況下,temp_f和位置)的斯威夫特?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> 
<script> 
jQuery(document).ready(function($) { 
    $.ajax({ 
    url : "http://api.wunderground.com/api/c1ea49b3e06dc3b3/geolookup/conditions/q/IA/Cedar_Rapids.json", 
    dataType : "jsonp", 
    success : function(parsed_json) { 
    var location = parsed_json['location']['city']; 
    var temp_f = parsed_json['current_observation']['temp_f']; 
    alert("Current temperature in " + location + " is: " + temp_f); 
    } 
    }); 
}); 
</script> 
+0

見http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial – Mitch

回答

0

雨燕相當於是

let url = NSURL(string:"http://api.wunderground.com/api/c1ea49b3e06dc3b3/geolookup/conditions/q/IA/Cedar_Rapids.json")! 
if let data = NSData(contentsOfURL: url) { 
    var error : NSError? 
    var city = "", temp_f = 0 
    if let jsonDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? [String:AnyObject] { 
    if let location = jsonDictionary["location"] as? [String:AnyObject] { 
     city = location["city"] as! String 
    } 
    if let observation = jsonDictionary["current_observation"] as? [String:AnyObject] { 
     temp_f = observation["temp_f"] as! Int 
    } 
    println("Current temperature in \(city) is: \(temp_f)") 
    } else { 
    println(error) 
    } 
} 
+0

謝謝!這幫助我認識到用swift解析JSON是多麼的麻煩:) –