2017-06-22 86 views
1

我需要這個函數(它從數據庫獲取一些數據)返回一個字符串,但我很難弄清楚如何。我已經發現了一些類似的問題/解決方案,但我仍然在努力實現一個妥善的解決辦法(我很新與SWIFT)從URLSession完成處理函數返回字符串Swift 3

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

謝謝!

+0

相當接近[此相關的問題的一種重複數據刪除(HTTPS:/ /stackoverflow.com/questions/24647406/how-to-use-completionhandler-closure-with-return-in-swift)。 –

回答

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