iOS後台定位

來源:互聯網
上載者:User

標籤:許可權   技術分享   需要   ref   dev   運行時   ice   nav   distance   

iOS地理定位 app正常運行時可以,按下home鍵後app在後台也可以,雙擊home鍵後台殺死app也可以,甚至重啟機器後也可以。(iOS 10 測試代碼)

1)設定一些請求參數

就像正常的CLLocationManager一樣申請許可權以及後台更新要求

後台更新:

plist請求地理位置(需要跑始終使用)

2)與往常一樣的初始化定位管理器等步驟

CLLocationManager *locationMgr = [[CLLocationManager alloc]init];

[locationMgr setAllowsBackgroundLocationUpdates:YES];

// 判斷手機是否啟用了定位服務

    if (![CLLocationManager locationServicesEnabled]) {

        NSLog(@"定位服務當前可能尚未開啟,請設定開啟!");

        return;

    }

    else {

        NSLog(@"定位服務已開啟");

    }

    //    如果沒有授權則請求使用者授權

    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){

        [locationMgr requestAlwaysAuthorization];

        NSLog(@"請求使用者授權");

    }else

    {

        NSLog(@"可以使用");

        locationMgr.delegate = self;

        locationMgr.desiredAccuracy = kCLLocationAccuracyBestForNavigation;

        locationMgr.distanceFilter = 0.1;

        

        locationMgr.allowsBackgroundLocationUpdates = YES;

        [locationMgr startUpdatingLocation];

        [locationMgr startMonitoringSignificantLocationChanges];

    }

// 如果地理位置發生了變化則走樓下回呼函數

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{}

3)設定後台與銷毀狀態的函數

// 終了時調用

 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hehe) name:@"OK" object:UIApplicationWillTerminateNotification];

// 後台時調用

 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hehe) name:@"OK" object:UIApplicationDidEnterBackgroundNotification];

-(void)hehe{

    [locationMgr startMonitoringSignificantLocationChanges];

    [locationMgr startUpdatingLocation];

}

------------->萬事大吉

注意:

1. APP被殺死,再開機時,回呼函數反應慢

2.這裡有startMonitoringSignificantLocationChanges和startUpdatingLocation兩個方法,一個是顯著位置變化一個是正常,前者被殺死也可喚起走入回呼函數,後者必須在APP沒死時才可以被喚起走入回呼函數。

附:

startMonitoringSignificantLocationChanges:

https://developer.apple.com/reference/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati

就是說就算被殺死也能通過顯著位置變化喚起的意思

startUpdatingLocation:

https://developer.apple.com/reference/corelocation/cllocationmanager/1423750-startupdatinglocation

就是說APP被殺死就不會通過位置變化而被喚起的意思

-=> 可以通過這樣開發一些需要APP自己啟動的APP嘍!(笑)

iOS後台定位

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.