iPhone 应用程序是否可以响应通过 Apple Watch 传输的文件(如果它处于非活动状态)?

Can the iPhone App respond to file transferred via Apple watch if it is inactive?

我正在开发一个 Apple Watch 应用程序,它记录一个音频文件,保存它,然后通过 WCSession(手表连接框架)将文件 URL 传输到 iPhone 应用程序。我的代码看起来像这样

在InterfaceController.m

NSURL *directory = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.name.watchtest"];
__block NSString *recordingName = @"myTestFile.mp4";
__block NSURL * outputURL = [directory URLByAppendingPathComponent:recordingName];

if ([WCSession isSupported]) {
   if ([self.watchSession isReachable]) {
         [self.watchSession transferFile:outputURL metadata:nil];
   }
}

在ViewController.m(WCSession 代表)

-(void)session:(WCSession *)session didReceiveFile:(WCSessionFile *)file
{
    NSError *error;
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                            NSUserDomainMask, YES);
    NSString *docsDir = [dirPaths objectAtIndex:0];
    NSFileManager *filemgr = [NSFileManager defaultManager];
    NSString *filePath = [docsDir stringByAppendingString:@"/myTestFile.mp4"];

    [filemgr moveItemAtPath:file.fileURL.path toPath:filePath error:&error];

    if ([filemgr fileExistsAtPath:file.fileURL.path]) {
        urlOfAudioFile = [[NSURL alloc] initFileURLWithPath:filePath];
        [self uploadToServer:urlOfAudioFile];
    }
}

如果 WatchApp 和 iPhone 应用程序都处于活动状态,这绝对可以正常工作。

当iPhone处于后台/不活动/锁定状态时,如何让它工作?

documentation on transferFile(_:metadata:) 明确指出:

Use this method to send a file that is local to the current device. Files are transferred to the counterpart asynchronously on a background thread. The system attempts to send files as quickly as possible but may throttle delivery speeds to accommodate performance and power concerns. Use the outstandingFileTransfers method to get a list of files that are queued for delivery but have not yet been delivered to the counterpart.

...

This method can only be called while the session is active—that is, the activationState property is set to activated. Calling this method for an inactive or deactivated session is a programmer error.

所以根据您的代码:

if ([WCSession isSupported]) {
   if ([self.watchSession isReachable]) {
         [self.watchSession transferFile:outputURL metadata:nil];
   }
}

如果 isSupportedisReachable 检查失败,则基本上 WCSession 处于非活动状态,您的代码将不会到达 transferFile(_:metadata:) 部分。
这是正确的行为,您必须手动处理这种情况。

但是... 当你有一个有效的会话并且 transferFile(_:metadata:) 确实被调用然后 iPhone 是否被锁定,或者应用程序正在后台,或者即使应用程序不是 运行,它也会通过后台线程接收文件。

所以回答你的问题,如果 iPhone 应用是 "inactive";如 isReachable 为 false,则文件传输不会发生。


参考: