最近在做一個(gè)后臺(tái)監(jiān)控流量的工具嚼酝,需要APP進(jìn)入后臺(tái)后,仍然可以執(zhí)行代碼進(jìn)行統(tǒng)計(jì)桑孩,但是iOS不像Android那樣有后臺(tái)服務(wù)拜鹤,進(jìn)入后臺(tái)后,一定時(shí)間后就會(huì)被掛起流椒。網(wǎng)上查了一些資料敏簿,在這里整理記錄下。
蘋果提供了一下幾種方式:
1.Audio and AirPlay
2.Location updates
3.Voice over IP
4.Newsstand downloads
5.External accessory communication
6.Uses Bluetooth LE accessories
7.Background fetch
8.Remote notifications
要使用它需要在Capabilities的Background Modes選中相應(yīng)的項(xiàng)宣虾。
我主要用到了2和7.
Location updates應(yīng)用退到后臺(tái)后惯裕,還可以得到系統(tǒng)定位更新,從而執(zhí)行一些代碼绣硝。
1.導(dǎo)入CoreLocation.framework,然后引用頭文件
2.開始定位
-(void)startLocation{
_locationManager = [[CLLocationManager alloc] init];
// 定位服務(wù)是否打開
if ([CLLocationManager locationServicesEnabled]) {
NSLog(@"開始執(zhí)行定位服務(wù)");
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 5;
_locationManager.delegate = self;
// 權(quán)限申請(qǐng)
if (IS_OS_8_OR_LATER) {
//[_locationManager requestWhenInUseAuthorization];
[_locationManager requestAlwaysAuthorization];
}
[_locationManager startUpdatingLocation];
}
}
3.在Info.plist文件中添加如下配置:
(1)NSLocationAlwaysUsageDescription
requestAlwaysAuthorization權(quán)限提示的文本信息
(2)NSLocationWhenInUseUsageDescription
requestWhenInUseAuthorization權(quán)限提示的文本信息
如果不設(shè)置這兩參數(shù)蜻势,是不會(huì)有權(quán)限提示,也不會(huì)后臺(tái)得到更新的消息域那。
4.設(shè)置實(shí)現(xiàn)代理CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
NSLog(@"定位更新 統(tǒng)計(jì)流量");
[self startOneFlowStatistic];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
NSLog(@"定位失敗: %@", error);
}
Background fetch是iOS7新增的咙边,在后臺(tái)iOS在間隔時(shí)間內(nèi)后臺(tái)啟動(dòng)該應(yīng)用。
1.設(shè)置間隔時(shí)間執(zhí)行
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
...
}
2.實(shí)現(xiàn)回調(diào)方法
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
NSLog(@"performFetchWithCompletionHandler");
[[FlowMonitorService shareFlowMonitorService] startOneFlowStatistic];
completionHandler(UIBackgroundFetchResultNewData);
}
參考地址:
iOS后臺(tái)運(yùn)行實(shí)現(xiàn)總結(jié) http://www.reibang.com/p/d3e279de2e32
iOS開發(fā):后臺(tái)運(yùn)行以及保持程序在后臺(tái)長(zhǎng)時(shí)間運(yùn)行 http://www.reibang.com/p/174fd2673897
iOS開發(fā)拓展篇—CoreLocation定位服務(wù)http://www.cnblogs.com/wendingding/p/3901230.html
iOS 7 SDK: 如何使用后臺(tái)獲却卧薄(Background Fetch) http://www.cocoachina.com/industry/20131114/7350.html