Add a return value to a closure [duplicate]

孤街醉人 提交于 2020-01-07 09:37:29

问题


I'm not very familiar with closure. I'm using this function to download a JSON file from a remote server

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()
}

Is it possible to make the function requestJson() return the JSON file when its loaded? Or it's not possible because it's loaded asynchronously and could not be ready? Want I'm trying to do is something like following:

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()
}

回答1:


You can give the function params an @escaping callback returning an array or whatever you need;

An example of this for a network request;

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

Then to call it you could do something like this;

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



回答2:


//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 
    })



回答3:


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

}

Usage:-

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

}


来源:https://stackoverflow.com/questions/45976216/add-a-return-value-to-a-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!