生活随笔
收集整理的這篇文章主要介紹了
iOS:后台定位并实时向服务器发送位置
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 第一步:開啟后臺模式,選中定位,選擇project --> capabilities-->Backgorund Modes --> Location updates 如圖:
允許 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> #import "ViewController.h"
@interface ViewController ()
@end@implementation ViewController
- (
void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor =
[UIColor whiteColor]; self.title =
@"后臺定位"; self.locationManager =
[[CLLocationManager alloc] init]; self.locationManager.delegate =
self; [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; if ([[UIDevice currentDevice].systemVersion floatValue] >
8) {/** 請求用戶權限:分為:只在前臺開啟定位 /在后臺也可定位, *//** 只在前臺開啟定位 */// [self.locationManager requestWhenInUseAuthorization];/** 后臺也可以定位 */ [self.locationManager requestAlwaysAuthorization]; } if ([[UIDevice currentDevice].systemVersion floatValue] >
9) {/** iOS9新特性:將允許出現這種場景:同一app中多個location manager:一些只能在前臺定位,另一些可在后臺定位(并可隨時禁止其后臺定位)。 */ [self.locationManager setAllowsBackgroundLocationUpdates:YES];} /** 開始定位 */ [self.locationManager startUpdatingLocation];
}
#pragma mark - 定位代理方法
- (
void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *
)locations { CLLocation *loc = [locations objectAtIndex:
0]; NSLog(@"經緯度 %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 that can be recreated.
}
@end 至此,完成后臺實時定位功能,并向服務器發送請求成功。
為原博主點贊吧:http://www.jianshu.com/p/0b339f1ff894
總結
以上是生活随笔為你收集整理的iOS:后台定位并实时向服务器发送位置的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。