我使用WatchConnectivity将图像从iOS传输到Watch OS。在模拟器中调试时,我面临一个问题
如我所见,文件已成功传输(发件人端,即iOS)
public func session(session: WCSession, didFinishFileTransfer fileTransfer: WCSessionFileTransfer, error: NSError?)现在从XCode我停止了iOS模拟器,将目标更改为Watch App,调用Ctrl+Run Watch App (只运行,不构建)方法下面的.The。
public func session(session: WCSession, didReceiveFile file: WCSessionFile) 我终于知道了
NSFileManager.defaultManager().moveItemAtURL(file.fileURL, toURL: destinationFileURL)这个调用会抛出,因为file.fileURL上没有文件(我也在我的MAC中签过)。
file.fileURL.path!是这样的
/Users/<user name>/Library/Developer/CoreSimulator/Devices/DAD8E150-BAA7-43E0-BBDD-58FB0AA74E80/data/Containers/Data/PluginKitPlugin/2CB3D46B-DDB5-480C-ACF4-E529EFBA2657/Documents/Inbox/com.apple.watchconnectivity/979DC929-E1BA-4C24-8140-462EC0B0655C/Files/EC57EBB8-827E-487E-8F5A-A07BE80B3269/image有什么线索吗?
发布于 2015-09-28 18:54:10
我发现了问题。我向主线程发送了一些代码,文件移动代码也在其中。WC框架在此方法结束后清理文件,因此必须在此函数返回之前移动该文件。我把代码移到performInMainThread块之外,一切都很有魅力。
public func session(session: WCSession, didReceiveFile file: WCSessionFile)
{
// Move file here
performInMainThread { () -> Void in
// Not here
}
}发布于 2015-12-01 19:04:25
正如苹果的WCSessionDelegate协议参考文档所指出的
- (无效)会话:(WCSession*)会话didReceiveFile:(WCSessionFile *)文件
返回(WCSessionFile *)文件参数时:
包含文件的URL和任何其他信息的对象。如果要保留此参数引用的文件,则必须在实现此方法期间同步将其移动到新位置。如果不移动该文件,系统将在此方法返回后删除该文件。
所以最好尽快把它搬到一个新的地方。它是安全的,因为系统保存了引用,并且在移动过程中不会删除它。
- (void)session:(WCSession *)session didReceiveFile:(WCSessionFile *)file {
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *cacheDir = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"];
NSURL *cacheDirURL = [NSURL fileURLWithPath:cacheDir];
if ([fileManager moveItemAtURL: file.fileURL toURL:cacheDirURL error: &error]) {
//Store reference to the new URL or do whatever you'd like to do with the file
NSData *data = [NSData dataWithContentsOfURL:cacheDirURL];
}
else {
//Handle the error
}
}警告!在后台队列中运行WCSession委托时,您必须小心线程处理,因此如果您想使用UI,就必须切换到主队列。
https://stackoverflow.com/questions/32828931
复制相似问题