簡體   English   中英

Swift如何在退出函數之前等待回調完成?

[英]Swift How to wait for callback to finish before exiting function?

我對此請求的問題是第一個函數syncRequest始終返回nil,因為函數退出(回復,錯誤)回來填寫我的返回字典。

有沒有辦法讓它在返回我的閉包之前等待回調返回?

public typealias KKWatchSyncResponse = Dictionary<String, AnyObject>

func syncRequest() -> KKWatchSyncResponse? {
    var syncResponseDict : KKWatchSyncResponse?
    createRequest(KKWatchRequest.Sync, parameter: nil) { reply, error in
        if reply == nil || error != nil {
            return
        } else {
            syncResponseDict = KKWatchSyncResponse()
        }
        if let songInfo = NSKeyedUnarchiver.unarchiveObjectWithData(reply!["songInfo"] as NSData) as NSDictionary? {
            syncResponseDict!["songInfo"] = songInfo
        }
        if let albumArtImage = NSKeyedUnarchiver.unarchiveObjectWithData(reply!["albumArt"] as NSData) as? UIImage {
            syncResponseDict!["albumArtImage"] = albumArtImage
        }
        if let isPlaying = NSKeyedUnarchiver.unarchiveObjectWithData(reply!["isPlaying"] as NSData) as? Bool {
            syncResponseDict!["isPlaying"] = isPlaying
        }
    }()
    return syncResponseDict
}

    func createRequest(request:KKWatchRequest, parameter: KKWatchAPIRequestParameter?, callback:KKWatchAPICallback) -> KKWatchAPIParentRequest {
       var requestDict : Dictionary<String, AnyObject> = [KKBOXWatchAppRequestType : request.rawValue]
        if parameter != nil {
        requestDict += parameter! //Combine 2 dictionaries
    }
        return { WKInterfaceController.openParentApplication(requestDict){ reply, error in
                callback(reply, error)
        }
    }
}

非常感謝您的幫助!

你可以讓syncRequest()接受一個在准備好后調用結果的閉包嗎? 將定義更改為:

func syncRequest(callback:(KKWatchSyncResponse?)->Void) { ... }

然后在createRequest()調用結束時,您可以在syncResponseDict上調用回調,因為現在它已經填充了您的數據... callback(syncResponseDict)

編輯:這是我想到的解決方案。

func syncRequest(callback:(KKWatchSyncResponse?)->Void) {
    createRequest(KKWatchRequest.Sync, parameter: nil) { reply, error in            
        if reply == nil || error != nil {
            callback(nil)
        } else {
            var syncResponseDict : KKWatchSyncResponse? = KKWatchSyncResponse()
            if let songInfo = NSKeyedUnarchiver.unarchiveObjectWithData(reply!["songInfo"] as NSData) as NSDictionary? {
                syncResponseDict!["songInfo"] = songInfo
            }
            if let albumArtImage = NSKeyedUnarchiver.unarchiveObjectWithData(reply!["albumArt"] as NSData) as? UIImage {
                syncResponseDict!["albumArtImage"] = albumArtImage
            }
            if let isPlaying = NSKeyedUnarchiver.unarchiveObjectWithData(reply!["isPlaying"] as NSData) as? Bool {
                syncResponseDict!["isPlaying"] = isPlaying
            }
            callback(syncResponseDict)
        }
    }()
}

實現鎖定變量是很簡單的。 這對於執行某些異步網絡加載的單元測試最有幫助。

func waitingFunction()
{
     //set a lock during your async function
     var locked = true
     RunSome.asyncFunction() { () -> Void in

       //after your sync function remove the lock
       locked = false
     })

     //wait for the async method to complete before advancing
     while(locked){wait()}

     //move on from the lock
     doMoreStuff()
}
func wait()
{
    NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate(timeIntervalSinceNow: 1))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM