iOS HTTP request while in background

前端 未结 2 1153
别跟我提以往
别跟我提以往 2020-11-30 05:54

It is possible to make HTTP async requests to PHP server while the app being in background? The app is a location based one, and should gather current location and send the

相关标签:
2条回答
  • 2020-11-30 06:36

    These links will help you out...

    iphone - Connecting to server in background

    0 讨论(0)
  • 2020-11-30 06:44

    It can be done but it is unreliable because you ask the OS for time to send something and it can accept or deny your request. This is what I have (stolen from somewhere on SO):

    [...] //we get the new location from CLLocationManager somewhere here    
    BOOL isInBackground = NO;
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
    {
        isInBackground = YES;
    }
    if (isInBackground)
    {
        [self sendBackgroundLocationToServer:newLocation];
    }
    
    
    - (void) sendBackgroundLocationToServer: (CLLocation *) lc
    {
        UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
        bgTask = [[UIApplication sharedApplication]
             beginBackgroundTaskWithExpirationHandler:^{
                 [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        }];
    
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
        [dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.latitude] forKey:@"floLatitude"];
        [dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.longitude] forKey:@"floLongitude"];
        // send to server with a synchronous request
    
    
        // AFTER ALL THE UPDATES, close the task
        if (bgTask != UIBackgroundTaskInvalid)
        {
            [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        }
    }
    
    0 讨论(0)
提交回复
热议问题