iOS项目开发实战——实现苹果本地消息通知推送服务

来源:互联网 发布:python入门视频 编辑:程序博客网 时间:2024/06/03 15:12

      当你一个App在后台运行时,有可能服务器会向你推送重要的信息,常见的如微信,QQ等,就算你的App在后台,也会以通知的形式给你推送。推送服务分为本地推送和在线推送。本次我们先来实现本地推送通知。

(1)代码实现如下:

#import "AppDelegate.h"#import "ViewController.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    return YES;}//程序从前台到后台时执行该方法;- (void)applicationDidEnterBackground:(UIApplication *)application{    //如果已经获得发送通知的授权则创建本地通知,否则请求授权(注意:如果不请求授权在设置中是没有对应的通知设置项的,也就是说如果从来没有发送过请求,即使通过设置也打不开消息允许设置)  if ([[UIApplication sharedApplication]currentUserNotificationSettings].types != UIUserNotificationTypeNone) {        [self addLocalNotification];  }else{    [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound  categories:nil]];  }  }//程序在后台运行,再次打开时回调该方法;此时取消badge数字;- (void)applicationWillEnterForeground:(UIApplication *)application{    [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];//进入前台取消应用消息图标}#pragma mark Notification-(void)addLocalNotification{    //定义本地通知对象  UILocalNotification *notification=[[UILocalNotification alloc] init];  //设置调用时间  notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:3.0];//通知触发的时间,10s以后  notification.repeatInterval = 2;//通知重复次数  //notification.repeatCalendar=[NSCalendar currentCalendar];//当前日历,使用前最好设置时区等信息以便能够自动同步时间    //设置通知属性  notification.alertBody=@"这是App推送的消息通知,哈哈"; //通知主体  notification.applicationIconBadgeNumber = 1;//应用程序图标右上角显示的消息数  notification.alertAction = @"打开应用"; //待机界面的滑动动作提示  notification.alertLaunchImage = @"Default";//通过点击通知打开应用时的启动图片,这里使用程序启动图片  //notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音,默认消息声音  notification.soundName = @"msg.caf";//通知声音(需要真机才能听到声音)    //设置用户信息  notification.userInfo=@{@"id":@1,@"user":@"Kenshin Cui"};//绑定到通知上的其他附加信息    //调用通知  [[UIApplication sharedApplication] scheduleLocalNotification:notification];}@end

(2)程序运行如下:





(3)我设置的是应用程序退出后3s推送通知。可以发现App图标有一个红色的badge,就如同微信的一样。点击进去后,badge会消失。根据你自己的逻辑,是不是就可以方便的使用了呢?当然安装时需要用户授权。



github主页:https://github.com/chenyufeng1991  。欢迎大家访问!


1 0