从URLSession完成处理程序函数返回字符串Swift 3

时间:2017-06-22 17:41:24

标签: ios swift swift3 nsurlsession completionhandler

我需要这个函数(从数据库中获取一些数据)来返回一个字符串但是我无法弄清楚如何。我发现了一些类似的问题/解决方案,但我仍在努力实施一个合适的解决方案(我对swift很新)

class Helper{
static func pReq(jsonURL : String, col : String) -> String {
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    let url  = URL(string: jsonURL)!
    let request = URLRequest(url: url)
    var string = ""

    let downloadTask = session.dataTask(with: request, completionHandler: {(data, response, error) in
        if(error == nil){ 
            print("data = \(String(describing: data))")
            do{
                print(jsonURL)
                let dataDownloadedAsJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]
                print("dataDownloadedAsJson = \(dataDownloadedAsJson)")
                do{

                    if(dataDownloadedAsJson[col] as? String != nil){
                        string = (dataDownloadedAsJson[col] as? String)!

                    }
                }
            }
            catch{
            }
        }
        else{
            print("Error downloading data. Error = \(String(describing: error))")
        }
    })
    downloadTask.resume()
    return string
}
}

谢谢!

1 个答案:

答案 0 :(得分:2)

您的session.dataTask(with:方法是异步的。这意味着它将“在后台”执行并告知您何时完成从其呼叫中获得响应。它会在“session.dataTask(with:”内的{}部分下方的块内通知您。好像出现了,您正在使用您收到的JSON进行一些处理,并将其格式化为您希望从此函数返回的字符串。 但是在您的通话完成之前,您已在底部呼叫return string,因此您将无法返回""。你真正需要做的不是从函数返回任何东西,而是使用完成块:

1)在你的档案上声明这个:

typealias StringCompletion      = (_ success: Bool, _ string: String) -> Void

2)修改你的功能以获取完成的参数

// This
static func pReq(jsonURL : String, col : String) -> String

// Becomes This
static func pReq(jsonURL : String, col : String, completion: @escaping StringCompletion)

3)在你的函数内部调用你的完成并传回Bool以表明这是一个成功的电话并传回string

class Helper{
static func pReq(jsonURL : String, col : String, completion: @escaping StringCompletion) {
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    let url  = URL(string: jsonURL)!
    let request = URLRequest(url: url)
    var string = ""

    let downloadTask = session.dataTask(with: request, completionHandler: {(data, response, error) in
        if(error == nil){ 
            print("data = \(String(describing: data))")
            do{
                print(jsonURL)
                let dataDownloadedAsJson = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]
                print("dataDownloadedAsJson = \(dataDownloadedAsJson)")
                do{

                    if(dataDownloadedAsJson[col] as? String != nil){
                        string = (dataDownloadedAsJson[col] as? String)! 
                        completion(true, string)
                    }
                }
                catch { completion(false, string) }
            }
            catch{
                completion(false, string)
            }
        }
        else{
            print("Error downloading data. Error = \(String(describing: error))")       
            completion(false, string)
        }
    })
    downloadTask.resume()
}
}

4)用法:

Helper().pReq(jsonURL: jsonURL, col: col) { (success, string) in
    if success {
        print("Success: \(string)")
    }
    else {
        print("Failure: Unable To Get String")
    }
}