向闭包添加返回值

时间:2017-08-31 07:58:44

标签: ios swift closures

我对闭合不是很熟悉。我正在使用此功能从远程服务器下载JSON文件

requestJson(){
    // Asynchronous Http call to your api url, using NSURLSession:
    NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://api.site.com/json")!, completionHandler: { (data, response, error) -> Void in
        // Check if data was received successfully
        if error == nil && data != nil {
            do {
                // Convert NSData to Dictionary where keys are of type String, and values are of any type
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
                // Access specific key with value of type String
                let str = json["key"] as! String
            } catch {
                // Something went wrong
            }
        }
    }).resume()
}

是否可以使函数requestJson()在加载时返回JSON文件?或者它不可能因为它是异步加载而无法准备好的?我想要做的就是跟随:

requestJson() -> **[String : AnyObject]**{
    // Asynchronous Http call to your api url, using NSURLSession:
    NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://api.site.com/json")!, completionHandler: { (data, response, error) -> Void in
        // Check if data was received successfully
        if error == nil && data != nil {
            do {
                // Convert NSData to Dictionary where keys are of type String, and values are of any type
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
                // Access specific key with value of type String
                **return json**
            } catch {
                // Something went wrong
            }
        }
    }).resume()
}

3 个答案:

答案 0 :(得分:1)

你可以给函数params一个@escaping回调返回一个数组或你需要的任何东西;

网络请求的一个示例;

class func getGenres(completionHandler: @escaping (genres: NSArray) -> ()) {
...
let task = session.dataTask(with:url) {
    data, response, error in
    ...
    resultsArray = results
    completionHandler(genres: resultsArray)
}
...
task.resume()
}

然后打电话给你,你可以做这样的事情;

override func viewDidLoad() {
    getGenres {
        genres in
        print("View Controller: \(genres)")     
    }
}

答案 1 :(得分:0)

//MARK: Request method to get json

class func requestJSON(completion: @escaping (returnModel: String?) -> Void) {
           //here you write code for calling API
  }

//MARK: Calling function to retrieve return string

API.requestJSON(completion: { (string) in
       //here you can get your string 
    })

答案 2 :(得分:-1)

func httpGet(request: NSURLRequest!, callback: (NSString, NSString?) -> Void)
{
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request){
    (data, response, error) -> Void in
    if error != nil {
        callback("", error.localizedDescription)
    } else {
        var result = NSString(data: data, encoding:
            NSASCIIStringEncoding)!
        callback(result, nil)
    }
}
task.resume()

}

func makeRequest(callback: (NSString) ->Void) -> Void {

var request = NSMutableURLRequest(URL: NSURL(string: "http://sample_url")!)

 var result:NSString = ""


httpGet(request){
    (data, error) ->  Void in

    if error != nil {
        result = error!
    } else {
        result = data
    }


    callback(data)
}

}

用法: -

 self.makeRequest(){
     (data) ->  Void in
    println("response data:\(data)")

}