iOS開發,ios開發教程
之前有做一個定位的項目,類似嘀嘀打車那樣。 需要後台持續定位。
這裡選擇了百度地圖,不過在後台持續定位方面, 之前只是簡單的設定如下:
不過經測試發現, 這樣設定完,在後台運行大概30分鐘,又會被crash掉。 重新開啟應用則自動回復定位。
當然,這不是我們想要的效果,所以折騰了下,實現了後台持續定位。
總的來說,就是利用進入後台後我們可操控的10分鐘,來完成一些事情。
為達到持續定位,每10分鐘。自動重新開啟定位。這樣就解決問題了。
具體如下:
AppDelegate.h
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier bgTask;
AppDelegate.m
- (void)backgroundHandler{ NSLog(@"### -->backgroundinghandler"); UIApplication* app = [UIApplication sharedApplication]; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Start the long-running task dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 您想做的事情, // 比如我這裡是發送廣播, 重新啟用定位 // 取得ios系統唯一的全域的廣播站 通知中樞 NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; //設定廣播內容 NSDictionary *dict = [[NSDictionary alloc]init]; //將內容封裝到廣播中 給ios系統發送廣播 // LocationTheme頻道 [nc postNotificationName:@"LocationTheme" object:self userInfo:dict]; }); }
- (void)applicationDidEnterBackground:(UIApplication *)application{ // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. BOOL backgroundAccepted = [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{ [self backgroundHandler]; }]; if (backgroundAccepted) { NSLog(@"backgrounding accepted"); } [self backgroundHandler];}
然後在開啟定位的位置,成為廣播接收者,並且重新啟用定位
//初始化BMKLocationService myLocService = [[BMKLocationService alloc]init]; myLocService.delegate = self; //啟動LocationService [myLocService startUserLocationService];
NSNotificationCenter *nc2 = [NSNotificationCenter defaultCenter]; // 成為聽眾一旦有廣播就來調用self recvBcast:函數 [nc2 addObserver:self selector:@selector(activeLocation:) name:@"LocationTheme" object:nil];
- (void) activeLocation:(NSNotification *)notify{ [myLocService stopUserLocationService]; //初始化BMKLocationService myLocService = [[BMKLocationService alloc]init]; myLocService.delegate = self; //啟動LocationService [myLocService startUserLocationService];}
當然,上面的方式,可能方法比較渣,代碼也寫的比較亂。
只是提供一種解決辦法而已。