Swift|Swift 百度API调用及json解析
1. 百度API调用
2.1 系统 NSJSONSerialization
2.2 第三方 SwiftyJSON
import UIKitclass ViewController: UIViewController {var json: AnyObject?
var dicData: NSDictionary!
var jsonSwity: JSON!override func viewDidLoad() {
super.viewDidLoad()let cityName = "beijing"
let apiKey = "--------your api key---------"
let callBack = APISCallBack()
let url = "http://apis.baidu.com/heweather/weather/free"
let method = "post"
let parameter = NSMutableDictionary()
parameter.setObject(cityName, forKey: "city")
ApiStoreSDK.executeWithURL(url, method: method, apikey: apiKey, parameter: parameter, callBack: callBack)callBack.onSuccess = { (status, responseString) -> Void in
NSLog("Success")
let data = responseString.dataUsingEncoding(NSUTF8StringEncoding)// 系统 NSJSONSerialization
self.json = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)// 第三方 SwiftyJSON
self.jsonSwity = JSON(data: data!)self.resolvingjson()
self.initLabelView()
}callBack.onError = { (status, responseString) -> Void in
NSLog("Error")
}callBack.onComplete = { () -> Void in
NSLog("Complete")
}
}// 解析json数据
func resolvingjson() {if let dict = json as? NSDictionary {
if let arr = dict["HeWeather data service 3.0"] as? NSArray {
if let dict2 = arr[0] as? NSDictionary {
if let dict3 = dict2["basic"] as? NSDictionary {self.dicData = https://www.it610.com/article/dict3
}
}
}
}}// initLabelView
func initLabelView() {
let label1 = UILabel(frame: CGRect(x: self.view.bounds.width/2 - 40, y: 50, width: 80, height: 40))
let label2 = UILabel(frame: CGRect(x: self.view.bounds.width/2 - 40, y: 100, width: 80, height: 40))
let label3 = UILabel(frame: CGRect(x: self.view.bounds.width/2 - 40, y: 150, width: 80, height: 40))
self.view.addSubview(label1)
self.view.addSubview(label2)
self.view.addSubview(label3)label1.text = dicData["city"] as? String
label2.text = dicData["cnty"] as? String// SwiftyJSON解析
label3.text = jsonSwity["HeWeather data service 3.0"][0]["status"].string
}
}
推荐阅读
- 投稿|Waymo、百度,自动驾驶杀死超级英雄
- Flink流处理API大合集(掌握所有flink流处理API技术,看这一篇就够了)
- Swift|Swift 2.0之错误处理(下)
- 百度输入法迅速打出空白字符绝招_百度输入法
- 计算机|使用Spring Boot和JPA创建GraphQL API
- 手把手带你入门 API 开发
- HaaS趣味案例|【毕设参考】跌倒检测 ESP32+HaaS Python Motion API 快速打造上云的跌倒检测系统
- Data|Web Scraping with Beautiful Soup for Data Scientist
- 详解docker|详解docker API管理接口增加CA安全认证
- 机器学习和深度学习|RealSense D435 的开发日记(API 汇总)