WatchKit return reply() inside a block in handleWatchKitExtensionRequest:

后端 未结 3 1919
自闭症患者
自闭症患者 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:05

    To make sure that your asynchronous data fetch does not return immediately (without calling reply), you may try the following:

    - (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void ( ^)( NSDictionary * ))reply
    { 
        __block UIBackgroundTaskIdentifier watchKitHandler;
    
        watchKitHandler = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"backgroundTask"
                                                                   expirationHandler:^{
                                                                       watchKitHandler = UIBackgroundTaskInvalid;
                                                                   }];  
    
       NSMutableDictionary *response = [NSMutableDictionary dictionary];
    
       dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    
       [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"]; 
    
                    dispatch_semaphore_signal(sema);
    
                    reply(response);
                }
                else
                {
                    [response setObject:@"update failed with no error" forKey:@"updateKey"];
    
                    dispatch_semaphore_signal(sema);
    
                    reply(response);
                }
            }
        }];
    
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
        dispatch_after(dispatch_time( DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC * 1), dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[UIApplication sharedApplication] endBackgroundTask:watchKitHandler];
      });
    }
    

提交回复
热议问题