-1

我來自C#背景,希望在我的Swift應用程序中實現等待功能。我已經達到了我想要的結果,但是我不得不使用信號量,我不確定這是一種好的做法。我有一個函數與alamo請求,返回一個JSON的成功值,據我所知,請求函數是一個完成處理程序異步。處理程序在請求完成後觸發。問題是從該操作返回成功值。下面是我正在做的一個僞代碼示例:「等待」Swift中的任務結果

func AlamoTest() -> Bool{ 
var success = false 
//Do some things... 
//... 
//Signal from async code 
let semaphore = DispatchSemaphore(value: 0) 
Alamofire.request("blah blah blah", method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in { 
    success = response["success"] 
    if(success){ 
     //Do some more things 
    } 
    semaphore.signal() //Signal async code is done 
} 
//Wait until async code done to get result 
semaphore.wait(timeout: DispatchTime.distantFuture) 
return success 
} 

有沒有一種「更好」的方式來實現我的目標?我是Swift及其異步構造的新手。

+0

反對嗎?真的嗎? – Seapoe

回答

0

我發現的最佳解決方案就是我所說的「回調鏈接」。我的方法的例子是這樣的:

func postJSON(json: NSDictionary, function: ServerFunction, completionHandler: ((_ jsonResponse: NSDictionary) -> Void)? = nil) { 
    //Create json payload from dictionary object 
    guard let payload = serializeJSON(json: json) else { 
     print("Error creating json from json parameter") 
     return 
    } 

    //Send request 
    Alamofire.request(urlTemplate(function.rawValue), method: .post, parameters: payload, encoding: URLEncoding.default).validate().responseJSON { response in 
     //Check response from server 
     switch response.result { 
      case .success(let data): 
       let jsonResponse = data as! NSDictionary 
       print("\(jsonResponse)") 
       //Execute callback post request handler 
       if completionHandler != nil { 
        completionHandler!(jsonResponse) 
       } 
      case .failure(let error): 
        print("Shit didn't work!\(error)") 
      } 
    } 
} 

最後一個參數是執行,一旦原單異步操作完成封閉。您將結果傳遞給關閉,並按照您的要求進行操作。在我的情況下,我想在異步操作滾動時禁用視圖。您可以在閉合參數中啓用視圖,因爲在主線程上調用了alamo異步操作的結果。如果您不需要結果並停止鏈接,completionHandler默認爲nil。

+0

https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f –