標籤:
蘋果在WWDC2014上正式公布了全新的iOS8作業系統。
介面上iOS8與iOS7相比變化不大,只是在功能方面進行了完好。
iOS8中更新和公開了非常多介面,當中有一項本地訊息通知UILocalNotification,大家肯定都不陌生。
可是在iOS8中對其進行了最佳化和改進。
如今它能夠依據地理位置發起訊息通知,即我們在App中設定好一個座標(經緯度)和半徑(範圍),當裝有本App的裝置進入本地區後,App就會發出一個訊息通知。
詳細操作例如以下:
1.要匯入我們須要的類庫CoreLocation.framework
2.登記位置資訊,擷取使用者的授權
CLLocationManager *locMan = [[CLLocationManager alloc] init];locMan.delegate = self;// request authorization to track the user’s location[locMan requestWhenInUseAuthorization];
同一時候還要進行配置plist檔案
當執行到最後一句時,使用者會收到系統提示,同意後app獲得授權。
3.擷取授權後app就會回調方法
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { // check status to see if we’re authorized BOOL canUseLocationNotifications = (status == kCLAuthorizationStatusAuthorizedWhenInUse); if (canUseLocationNotifications) { [self startShowingLocationNotifications]; }}回調方法裡注冊通知
- (void)startShowingNotifications { UILocalNotification *locNotification = [[UILocalNotification alloc] init]; locNotification.alertBody = @“You have arrived!”; locNotification.regionTriggersOnce = YES; locNotification.region = [[CLCircularRegion alloc] initWithCenter:LOC_COORDINATE radius:LOC_RADIUS identifier:LOC_IDENTIFIER]; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];}//- (instancetype)initWithCenter:(CLLocationCoordinate2D)center //地區的中心 經緯度// radius:(CLLocationDistance)radius //地區半徑 範圍// identifier:(NSString *)identifier; //通知的唯一標示 描寫敘述
4.到了一定地區後觸發訊息通知。收到訊息後app回調方法
-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region{ NSLog(@"%s",__func__);}- (void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification{ CLRegion *region = notification.region; if (region) { [self tellFriendsUserArrivedAtRegion:region]; }}
註:
查看官方文檔,瞭解很多其它UILocalNotification 新增API。
本服務須要位置資訊登記;
假設位置資訊被禁用。這種方法application:didReceiveLocalNotification: 就不會被調用。
iOS8新特性之基於地理位置的訊息通知UILocalNotification