Swift 百度API调用及json解析

1. 百度API调用

2.1 系统 NSJSONSerialization

2.2 第三方 SwiftyJSON

    import UIKit

    class 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 = 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
        }
    }

你可能感兴趣的:(Swift 百度API调用及json解析)