Swift - 从模型中的API调用返回JSON对象以在View Controller中使用

时间:2015-06-21 13:04:58

标签: ios json swift dictionary

我最近开始尝试使用Swift,并且是更强类型编程语言的新手。

我正在尝试构建一个对http://openweathermap.org/api的基本API调用,该调用将在UIView中有一个搜索框,该搜索框采用城市名称并返回相关的天气数据。

我的问题是弄清楚如何返回我在模型中作为字典的API调用返回的JSON响应,然后我可以将其用作我的ViewController中的变量。

我已经尝试了各种方法,但继续得到'Dictionary not convertible to Void'错误。从研究和本文(Dictionary is not convertible to Void)来看,似乎返回一个闭包可能提供答案,但我正在努力实现,因为我只想在我的ViewController searchButton函数中传递一个cityname字符串参数。

下面有详细的代码段,感谢您的帮助!

我在下面的模型中调用API,它目前用于下拉JSON对象

class API {
func weatherSearch(#urlSearch: String) -> Dictionary<String,AnyObject>
{
    let urlPath = "http://api.openweathermap.org/data/2.5/weather?q=" + urlSearch
    let url = NSURL(string: urlPath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        println("Task completed")
        if(error != nil) {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }
        var err: NSError?
        if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
            var dataOut = jsonResult as Dictionary<String,AnyObject>
            return dataOut
         //omitted some additional error handling code
        }
    })
    task.resume()
 }
}

我的ViewController实例化API并从Searchfield获取输入

@IBOutlet weak var searchField: UITextField!

@IBAction func searchButton() {
    let api = API()
    var dataOut = api.weatherSearch(urlSearch: searchField.text!)
    println(dataOut)
    self.performSegueWithIdentifier("Search", sender: nil)
}

1 个答案:

答案 0 :(得分:2)

使用上面评论暗示的回调技术,尝试类似这样的

func weatherSearch(#urlSearch: String, callback: (Dictionary<String,AnyObject> -> ())) {
    let urlPath = "http://api.openweathermap.org/data/2.5/weather?q=" + urlSearch
    let url = NSURL(string: urlPath)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        println("Task completed")
        if(error != nil) {
            // If there is an error in the web request, print it to the console
            println(error.localizedDescription)
        }
        var err: NSError?
        if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
            var dataOut = jsonResult as! Dictionary<String,AnyObject>
            callback(dataOut)
            //omitted some additional error handling code
        }
    })
    task.resume()
}

weatherSearch(urlSearch: "endpoint here") { dictionary in
    println(dictionary)
}