推送通知分为两种:本地推送通知(Local Notification) 和 远程推送通知(Remote Notification)
一、本地通知
无需网络连接
当应用处于非前台状态的时候(无论是锁屏、后台、还是未运行),如果用户点击了通知,便会打开应用程序。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//iOS8.0 以后,发送本地通知需要添加的代码,效果见下图
if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.f) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
[application registerUserNotificationSettings:settings];
}
return YES;
}
必须获取用户权限:
发送通知代码:
- (IBAction)pressSend:(id)sender {
UILocalNotification *local = [[UILocalNotification alloc] init];
local.fireDate = [NSDate dateWithTimeIntervalSinceNow:5.f];
local.alertBody = @"我是本地通知";
local.applicationIconBadgeNumber = 999;
[[UIApplication sharedApplication] scheduleLocalNotification:local];
}
其他属性:
- (instancetype)init NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
// timer-based scheduling
@property(nullable, nonatomic,copy) NSDate *fireDate;
// the time zone to interpret fireDate in. pass nil if fireDate is an absolute GMT time (e.g.