Refresh location when a task starts when the application is in the background. But failed to complete the task in the background. My sample code with scheduleBackgroundRefreshWithPreferredDate looks below
[WKExtension.sharedExtension scheduleBackgroundRefreshWithPreferredDate:[NSDate dateWithTimeIntervalSinceNow:60] userInfo:nil scheduledCompletion:^(NSError * _Nullable error) { if(error == nil) { NSLog(@"background refresh task re-scheduling successfuly "); } else{ NSLog(@"Error occurred while re-scheduling background refresh: %@",error.localizedDescription); } }];
After completing the schedule task in handleBackgroundTasks:
- (void)handleBackgroundTasks:(NSSet<WKRefreshBackgroundTask *> *)backgroundTasks { for (WKRefreshBackgroundTask * task in backgroundTasks) { if ([task isKindOfClass:[WKApplicationRefreshBackgroundTask class]]) { WKApplicationRefreshBackgroundTask *backgroundTask = (WKApplicationRefreshBackgroundTask*)task;
Background task methods as shown below
-(void)startLocationUpdate { locationMgr = [[CLLocationManager alloc] init]; [locationMgr setDelegate:self]; locationMgr.desiredAccuracy = kCLLocationAccuracyBest; locationMgr.distanceFilter = kCLDistanceFilterNone; // locationMgr.allowsBackgroundLocationUpdates = YES; [locationMgr requestAlwaysAuthorization]; [locationMgr startUpdatingLocation]; [WKExtension.sharedExtension scheduleBackgroundRefreshWithPreferredDate:[NSDate dateWithTimeIntervalSinceNow:60] userInfo:nil scheduledCompletion:^(NSError * _Nullable error) { if(error == nil) { NSLog(@"background refresh task re-scheduling successfuly "); } else{ NSLog(@"Error occurred while re-scheduling background refresh: %@",error.localizedDescription); } }]; } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { NSTimeInterval locationAge = -[[locations lastObject].timestamp timeIntervalSinceNow]; NSLog(@"Location Age : %f",locationAge); if (locationAge > 5.0) return; NSLog(@"latitude: %f longitude: %f",[locations lastObject].coordinate.latitude,[locations lastObject].coordinate.longitude); //NSString *strLocation = [NSString stringWithFormat:@"%f,%f" ,[locations lastObject].coordinate.latitude , [locations lastObject].coordinate.longitude]; NSString *strLocation = @"bgLocation"; NSDictionary *applicationData = [[NSDictionary alloc] initWithObjects:@[strLocation] forKeys:@[@"watchlocation"]]; [[WCSession defaultSession] transferUserInfo:applicationData]; }
source share