我设置了 UIBackgroundModes 键,这部分可以很好地将位置写入屏幕。
由于您已经在使用后台模式,因此 GPS 功能有望正常工作。
即使应用程序在后台,消息也需要发送到服务器。
该应用程序获得大约 10 分钟的后台运行时间,然后被 iOS 强制暂停。
//Check if device supports multi-tasking
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
//Get the shared application instance
UIApplication *application = [UIApplication sharedApplication];
//Create a task object
__block UIBackgroundTaskIdentifier background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
//Tell the system that we are done with the tasks
[application endBackgroundTask: background_task];
//Set the task to be invalid
background_task = UIBackgroundTaskInvalid;
//System will be shutting down the app at any point in time now
}];
//Background tasks require you to use asynchronous tasks
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//Perform your tasks that your application requires
NSLog(@"\n\nRunning in the background!, here we can send the request to server for 10 minutes.");
//End the task so the system knows that you are done with what you need to perform
[application endBackgroundTask: background_task];
//Invalidate the background_task
background_task = UIBackgroundTaskInvalid;
});
}
即使在生成消息时设备处于离线状态,消息也需要发送到服务器(用户在获取 gps 位置时通常会超出小区范围)。当然,这些消息不必立即发送,但应该在设备重新联机时存储和发送。
对于这个功能,创建一个 HTTP Singleton 类,并检查互联网是否可用。同时激活网络变化通知,这样,如果应用程序在使用过程中获得网络连接,应用程序可以将记录上传到服务器。对于在服务器上上传记录,您可以在 GCD 中创建自己的 NSURLConnections 以支持多连接,也可以使用GCDAsyncSocket第三方开源库。