首先,我使用"transferUserInfo"-method将字典从iPhone发送到Apple:
let dicty = //...my dictionary of property-list values...
if WCSession.isSupported() {
let session = WCSession.defaultSession()
if session.paired == true { // Check if your Watch is paired with your iPhone
if session.watchAppInstalled == true { // Check if your Watch-App is installed on your Watch
session.transferUserInfo(dicty)
}
}
}然后,我使用以下委托回调方法"didFinishUserInfoTransfer“来检查传输的状态:
func session(session: WCSession, didFinishUserInfoTransfer userInfoTransfer: WCSessionUserInfoTransfer, error: NSError?) {
if error == nil {
let session = WCSession.defaultSession()
let transfers = session.outstandingUserInfoTransfers
if transfers.count > 0 { //--> is always > 0, why ?????????
for trans in transfers {
trans.cancel() // cancel transfer that will be sent by updateApplicationContext
let dict = trans.userInfo
session.transferUserInfo(dict) //--> creates enless-transfer cycle !!!!!
}
}
}
else {
print(error)
}
}在Apple中,它介绍了didFinishUserInfoTransfer方法:
The session object calls this method when a data transfer initiated by the
current app finished, either successfully or unsuccessfully. Use this method
to note that the transfer completed or to respond to errors, perhaps by
trying to send the data again at a later time.到目前为止还不错-我明白。但现在-有件事我不明白:
如果输入didFinishUserInfoTransfer而错误==为零,为什么session.outstandingUserInfoTransfers计数可以大于0?
根据苹果文档,didFinishUserInfoTransfer的唯一非错误状态应该是在传输结束时!!它似乎还没有结束..。为什么?
谢谢你对此作出任何澄清。
而且,我也很高兴看到任何关于如何正确使用这3种方法的示例代码!(即:
发布于 2016-01-14 16:53:27
在委托回调返回之前,似乎不会将触发didFinishUserInfoTransfer回调的didFinishUserInfoTransfer从outstandingUserInfoTransfers中删除。要获得您想要的行为(计数可以降到0),您需要从委托回调线程中dispatch_async。所以这应该是可行的:
func session(session: WCSession, didFinishUserInfoTransfer userInfoTransfer: WCSessionUserInfoTransfer, error: NSError?) {
if error == nil {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
let transfers = session.outstandingUserInfoTransfers
if transfers.count > 0 { //--> will in most cases now be 0
for trans in transfers {
trans.cancel() // cancel transfer that will be sent by updateApplicationContext
let dict = trans.userInfo
session.transferUserInfo(dict) // ***
}
}
});
}
else {
print(error)
}
}尽管如此,我不太明白为什么您会想要取消所有剩余的未完成的userInfoTransfers,只要它们完成,只是重新排队(有问题的位置由***指示)。
发布于 2017-05-22 15:53:22
就我阅读这些文档而言,有一点误解:只有在发生错误时,才会再次发送。如果未引发错误,则具有未执行的userInfoTransfers是预期的行为;它们尚未成功发送,并且仍在排队。
顺便说一句。代码使用实际的dispatchQueue。
func session(_ session: WCSession, didFinish userInfoTransfer: WCSessionUserInfoTransfer, error: Error?) {
if error != nil { // resend if an error occured
DispatchQueue.main.async {
let transfers = session.outstandingUserInfoTransfers
if transfers.count > 0 {
// print("open transfers: \(transfers.count)")
for trans in transfers {
// print("resend transfer")
trans.cancel() // cancel transfer
let dict = trans.userInfo
session.transferUserInfo(dict) // send again
}
}
}
}
}https://stackoverflow.com/questions/34772965
复制相似问题