30
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WatchKit App と iOS App 間でやり取りしつつ、iOS App に割りと長めの処理を実行させる

Posted at

iOS App がフォアグラウンドにあるときはうまくいくのに background にあるとうまくいかない、などでハマらないように。

iOS App 側

application:handleWatchKitExtensionRequest:reply: の実装

AppDelegate に実装します。

- (void)application:(UIApplication *)application
handleWatchKitExtensionRequest:(NSDictionary *)userInfo
              reply:(void (^)(NSDictionary *replyInfo))reply
{
    // do something...
}

beginBackgroundTaskWithName:expirationHandler: あるいは beginBackgroundTaskWithExpirationHandler: で background 処理を継続させる

公式ドキュメントの Execution States for Apps 欄 にあるように、アプリは background に移るとほどなくして suspended になり、なんのコードも実行しなくなります。
長めの処理を iOS App 側にさせる場合それだと困るので、こちらの Executing Finite-Length Tasks に従って background 処理を継続させます。

- (void)application:(UIApplication *)application
handleWatchKitExtensionRequest:(NSDictionary *)userInfo
              reply:(void (^)(NSDictionary *replyInfo))reply
{
    __block UIBackgroundTaskIdentifier bgTask;
    bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
 
    // この辺で長い処理とか。GCD を使うなど。
    reply( hoge );

    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}

WatchKit Extension 側

Controller などで openParentApplication:reply: を呼び出す。

ドキュメントはこちら

30
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?