Skip to main content
 首页 » 操作系统

Swift 如何在退出函数之前等待回调完成

2024年01月01日32zfyouxi

我在这个请求中遇到的问题是第一个函数 syncRequest 总是返回 nil,因为该函数在 (reply, error) 返回以填充我的返回字典之前退出。

有没有办法让它在从我的闭包中返回之前等待回调返回?

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 上调用回调,因为现在它已经填充了您的数据... 回调(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) 
        } 
    }() 
}