使用Swift解析GET请求

时间:2015-07-12 19:53:00

标签: swift

所以我从Wunderground的weather api文档中得到了这个示例代码:stands for the character 效

如何在Swift中获取相同的信息(在本例中为temp_f和location)?

<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>

1 个答案:

答案 0 :(得分:0)

Swift等价物是

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)
  }
}
相关问题