[英]How to get and send location(even if application is terminated or suspended) to server
即使應用程序終止,我也需要獲取位置並將其發送到服務器,我找到了如何獲取位置的解決方案,但是如何將其發送到服務器-我找不到。 我想我可以通過后台任務發送它,但是它如何一起工作,我無法想象,我嘗試使用此代碼indidFinishLaunchingWithOptions:
if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
// This "afterResume" flag is just to show that he receiving location updates
// are actually from the key "UIApplicationLaunchOptionsLocationKey"
self.shareModel.afterResume = YES;
[self.shareModel startMonitoringLocation];
[self.shareModel addResumeLocationToPList];
UIApplication *application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[NSUserDefaults standardUserDefaults] setObject:str forKey:@"DOWNLOADTASK"];
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
但是比我通過此鍵打印NSUserDefaults它為空,我做錯了,可能是我使用了錯誤的后台任務?
根據蘋果文件中有關后台的描述,任何應用程序后台任務的執行時間為10分鍾。10分鍾后,該應用程序將被iOS強制掛斷。 但是有五種類型的應用程序允許“無限”的后台運行時間。
音頻。
位置/ GPS。
VoIP。
報攤。
外部配件。
您可以采用上述五種類型的任何應用程序語句來獲取無限時間的背景,但是當您將應用程序提交到應用程序商店時,Apple將審查您的應用程序,一旦發現您“濫用”了后端API,您的應用將被拒絕。 但是,在企業開發的情況下,不存在“濫用”問題-企業應用程序可以通過OTA部署,而無需通過蘋果商店審查。 在企業部署中,您可以聲明VoIP應用程序,但該程序與VoIP無關,我們僅出於iOS的目的,賦予我們無限的后台執行權限。聲明過程在應用程序信息中。 要添加以下密鑰的文件:首先,在文件的必需背景模式中添加以下兩種:在App中播放音頻或使用AirPlay播放音頻/視頻流,並且App提供IP語音服務。 UIBackgroundModes
語音
我測試了以下代碼:
- (void)backgroundHandler {
NSLog(@"### -->backgroundinghandler");
UIApplication* app = [UIApplicationsharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
通過測試,我收到了“無限”的后台執行時間。我不知道您認為“無限”有多長時間,但是在這種情況下,后台任務要運行至少55小時,直到我失去耐心為止停止測試。 我的英語很差,此博客轉載!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.