First step, turn on background mode, select targeting, select Project--Capabilities-->backgorund Modes--Location updates
Paste_image.png
The second step is to add the following configuration to the Info.list file:
允许 http 请求 ,ios 9 之后需要添加,便于向服务器发送请求<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
添加定位权限,ios8之后需要添加,否则无法定位<key>NSLocationWhenInUseUsageDescription</key> <string>YES</string> <key>NSLocationAlwaysUsageDescription</key> <string>YES</string>
The third step, the code is as follows:
#import "ViewController.h"@interfaceViewcontroller ()@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //additional setup after loading the view, typically from a nib.Self.view.backgroundColor=[Uicolor Whitecolor]; Self.title=@"Background Positioning"; Self.locationmanager=[[Cllocationmanager alloc] init]; Self.locationmanager.Delegate=Self ; [Self.locationmanager Setdesiredaccuracy:kcllocationaccuracybest]; if([[Uidevice currentdevice].systemversion Floatvalue] >8) { /** Request User rights: Divided into: Only in the foreground to open the location/in the background can also be located,*/ /** Only open the location at the front desk*///[Self.locationmanager requestwheninuseauthorization]; /** Background can also be located*/[Self.locationmanager requestalwaysauthorization]; } if([[Uidevice currentdevice].systemversion Floatvalue] >9) { /** IOS9 new feature: This scenario will be allowed: multiple location managers in the same app: some can only be located in the foreground, others can be located in the background (and can be disabled at any time in the background location). */[Self.locationmanager Setallowsbackgroundlocationupdates:yes]; } /** Start positioning*/[Self.locationmanager startupdatinglocation];}#pragmaMark-Location Agent Method-(void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (nsarray<cllocation *> *) locations{cllocation*loc = [Locations Objectatindex:0]; NSLog (@"latitude and longitude of%f%f", Loc.coordinate.latitude,loc.coordinate.longitude); Nsurlsession*session =[Nsurlsession sharedsession]; Nsurlsessiondatatask*task = [Session datataskwithrequest:[nsurlrequest Requestwithurl:[nsurl URLWithString:@"http://ac.ybjk.com/ua.php"]] completionhandler:^ (NSData * _nullable data, Nsurlresponse * _nullable response, Nserror *_nullable Error) {//NSLog (@ "Response%@", response);NSString*result =[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"result%@", result); }]; [Task resume];}- (void) didreceivememorywarning {[Super didreceivememorywarning]; //Dispose of any resources the can be recreated.}@end
iOS background location, send the latest position to the server in real time