2017-03-13 99 views
0

我正在處理一小段Swift代碼,以通過基於Web的API提取數據。現在我接近了,但是當我在getUserInfo()中打印數據時,認爲我缺少完成處理程序方面的預期數據,但在該函數外部,出現了初始化的默認數據。該功能被稱爲像這樣:向Alamofire添加完成處理程序

print("Provided Username is: \(workingData.user)") 
getUserInfo() 
print("Returned String Data is: \(workingData.responseDataString)") 

和實際的功能:

func getUserInfo() { 
    Alamofire.request(workingjss.jssURL + devAPIMatchPath + workingData.user, method: .get) 
     .authenticate(user: workingjss.jssUsername, password: workingjss.jssPassword).responseString { response in 
      if (response.result.isSuccess) { 
       print("In Function Data: \(response.result.value!)" 
       workingData.responseDataString = response.result.value! 
      } 
    } 
} 

中運行代碼的輸出是:

Provided Username is: MYUSER 
Returned String Data is: Nothing Here Yet 
In Function Data: {"Cleaned JSON Data here"} 

會完成處理程序幫助的問題了呢?我非常喜歡與Alamofire合作,所以很抱歉,如果這是一件容易的事情。謝謝!

回答

4

嘗試使用完成處理程序:

func getUserInfo(completion: @escaping (String) -> Void) { 
    Alamofire.request(workingjss.jssURL + devAPIMatchPath + workingData.user, method: .get) 
     .authenticate(user: workingjss.jssUsername, password: workingjss.jssPassword).responseString { response in 
      if (response.result.isSuccess) { 
       print("In Function Data: \(response.result.value!)" 
       completion(response.result.value!) 
      } 
    } 
} 

,並調用它像:

getUserInfo() { response in 
    // Do your stuff here 
    workingData.responseDataString = response 
    print("Returned String Data is: \(workingData.responseDataString)") 
}