ios (推送)之本地推送
iOS上有兩種訊息通知,一種是本地訊息(Local Notification),一種是遠程訊息(Push Notification,也叫Remote Notification),設計這兩種通知的目的都是為了提醒使用者,現在有些什麼新鮮的事情發生了,吸引使用者重新開啟應用。本地推送也可以通過伺服器控制,比如說如果有新訊息了,推送訊息,但是,前提是程式必須是開啟的,而遠程推送,是通過蘋果APNS伺服器,推送給手機,手機在推送給具體的哪個程式,一般遠程推送用到的比較多,先介紹下本地推送,下節在介紹遠程推送。
本地推送:
首先,先在appdelegate中註冊:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];//註冊本地推送 // Override point for customization after application launch. return YES;}
然後,在具體的viewcontroller中實現推送:
- (IBAction)localPushNow:(id)sender { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //本地推送 UILocalNotification*notification = [[UILocalNotification alloc]init]; NSDate * pushDate = [NSDate dateWithTimeIntervalSinceNow:10]; if (notification != nil) { notification.fireDate = pushDate; notification.timeZone = [NSTimeZone defaultTimeZone]; notification.repeatInterval = kCFCalendarUnitDay; notification.soundName = UILocalNotificationDefaultSoundName; notification.alertBody = @"hello,world"; notification.applicationIconBadgeNumber = 0; NSDictionary*info = [NSDictionary dictionaryWithObject:@"test" forKey:@"name"]; notification.userInfo = info; [[UIApplication sharedApplication] scheduleLocalNotification:notification]; } });}
在appdelegate中會接收到推送資訊:
//接收本地推送
//接收本地推送- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{ NSLog(@"%@",notification.alertBody); UILabel*label = [[UILabel alloc]init]; label.frame = CGRectMake(0, 0, 160, 20); label.layer.cornerRadius = 10; label.backgroundColor = [UIColor blackColor]; label.text = notification.alertBody; label.textColor = [UIColor whiteColor]; label.font = [UIFont systemFontOfSize:12]; label.textAlignment = NSTextAlignmentCenter; [self.window addSubview:label];}
過程中可能會出現如下狀況:
Attempting to schedule a local notification……with a sound but haven't received permission from the user to play sounds
Attempting to schedule a local notification……with an alert but haven't received permission from the user to display alerts
可能是因為你沒有註冊,或者設定中沒有開啟推送功能,