2

I am developing an apple watch application which records an audio file, saves it and then transfers the file URL to the iPhone app via WCSession (Watch Connectivity framework). My code looks like this

In 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];
   }
}

In ViewController.m (WCSession delegate)

-(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];
    }
}

This works absolutely fine if both the WatchApp & the iPhone App are Active.

How can I make it work when the iPhone is in the background/ inactive/ in the locked state?

4

1 回答 1

3

文件上transferFile(_:metadata:)明确指出:

使用此方法发送当前设备的本地文件。文件在后台线程上异步传输到对方。系统会尝试尽快发送文件,但可能会限制传输速度以适应性能和功耗问题。使用出色的FileTransfers 方法获取排队等待交付但尚未交付给对方的文件列表。

...

此方法只能在会话处于活动状态时调用——即,activationState 属性设置为已激活。为非活动或停用的会话调用此方法是程序员错误。

所以根据你的代码:

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

如果isSupported&isReachable检查失败,则基本上WCSession是不活动的,您的代码将无法到达该transferFile(_:metadata:)部分。
这是正确的行为,您必须手动处理这种情况。

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

因此,要回答您的问题,如果 iPhone 应用程序“不活动”;as inisReachable为 false 则不会发生文件传输。


参考:

于 2018-04-09T12:17:21.630 回答