WatchKit return reply() inside a block in handleWatchKitExtensionRequest:

后端 未结 3 1916
自闭症患者
自闭症患者 2021-01-21 14:15

I saw this SO post where apparently data was being fetched and returned to the Watch extension like so:

- (void)application:(UIApplication *)application handleWat         


        
3条回答
  •  不要未来只要你来
    2021-01-21 15:00

    Always refer to official documentation. Official Documentation

    The following code works for me.

    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
                    // Clean up any unfinished task business by marking where you
                    // stopped or ending the task outright.
                    [application endBackgroundTask:bgTask];
                    bgTask = UIBackgroundTaskInvalid;
            }];
    
    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
    // Do the work associated with the task, preferably in chunks.
    
        [ClassObject getDataWithBlock:^(BOOL succeeded, NSError *error){
    
            if (succeeded)
            {
                [response setObject:@"update succeded" forKey:@"updateKey"];
                reply(response);
    
            }
            else
            {
                if (error)
                {
                    [response setObject:[NSString stringWithFormat:@"update failed: %@", error.description] forKey:@"updateKey"]; 
    
                    reply(response);
                }
                else
                {
                    [response setObject:@"update failed with no error" forKey:@"updateKey"];
    
                    reply(response);
                }
            }
        }];
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
    

提交回复
热议问题