我想制作一个 iOS7 设计,以使用 3G/4G/LTE(非 WiFi)从后台将其位置上传到服务器,频率低于每 5 到 10 分钟一次,或者当它的位置发生变化时。
我已经尝试过的是这样的:
1.后台获取
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
叫得这么不规律,不可控。
2.远程通知(非静音推送)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
仅在 WiFi 连接中调用。
3.CLLocationManager
我把上传器放进去,- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
但它只在 WiFi 上被调用。
我想实现一个像“Find Your Friends”这样的应用程序,它是 iOS8 中的 Apple 原生应用程序。有什么想法吗?
谢谢您的帮助。
更新
我尝试通过如下NSURLSession upload
方式触发,但它仍然只在 WiFi 上上传。CLLocationManager didUpdateToLocation
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[[NSUserDefaults standardUserDefaults] setFloat:newLocation.coordinate.latitude forKey:@"lat"];
[[NSUserDefaults standardUserDefaults] setFloat:newLocation.coordinate.longitude forKey:@"lon"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self update];
}
- (void)update
{
NSURL *url = [NSURL URLWithString:@"http://.../updater.php"];
NSString *identifier = [NSDate date].description;
NSURLSessionConfiguration *configration = [NSURLSessionConfiguration backgroundSessionConfiguration:identifier];
configuration.networkServiceType = NSURLNetworkServiceTypeBackground;
configuration.discretionary = NO;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"PUT";
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
float lat = [[NSUserDefaults standardUserDefaults] floatForKey:@"lat"];
float lon = [[NSUserDefaults standardUserDefaults] floatForKey:@"lon"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:lat], @"lat",
[NSNumber numberWithFloat:lon], @"lon", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *path = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"json.data"];
[data writeToFile:path atomically:YES];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:path]];
[task resume];
}
- (NSURL *)applicationDocumentsDirectory
{
// The directory the application uses to store the Core Data store file. This code uses a directory named "jp.skyElements.NNZ" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}