-->

Will Realm still be able to save the data while us

2019-09-16 16:40发布

问题:

I am trying to save some data to Ream database while users have locked their iPhone. Thie data may be the location coordinate which produced by background location updates. If realm can't do it. Could Core Data do it?

This is how I do it in code:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"didUpdateLocations: %@", locations);

    if (locations.count > 0) {
        CLLocation *location = locations.firstObject;

        if (location.horizontalAccuracy < 0) {
            return;
        }

        JBLocation *locationObject = [[JBLocation alloc] init];
        locationObject.lat = location.coordinate.latitude;
        locationObject.lon = location.coordinate.longitude;
        locationObject.date = [NSDate new];
        locationObject.speed = location.speed;

        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm beginWriteTransaction];
        [realm addObject:locationObject];
        [realm commitWriteTransaction];
    }
}

回答1:

Doing something while the phone is locked is an example of a background task. Though I'm not sure if you will be successful in doing a task in the background even for once, but it is certain that when the OS kills your app, it can't do what you want to do any longer.

I'm doing in a project that is similar to yours (background location fetching, saving to local database the data, posting to the server while the screen is locked.) It is already complete but waiting for release signal. It was also submitted (approved) to the Apple as Beta.

I used this sample project as a library and ported to Swift:

https://github.com/voyage11/Location