美文网首页iOS开发进阶
iOS8 本地推送 UILocalNotification

iOS8 本地推送 UILocalNotification

作者: 安静守护你 | 来源:发表于2018-07-25 15:43 被阅读6次

前言

最近忙中偷闲,把有关本地推送的内容给整理一下,本篇文章主要讲述UILocalNotification的一些使用,下篇文章会在此基础上介绍其替代品UNUserNotificationCenter

UILocalNotification的使用

在iOS8及其之后的推送都使用UILocalNotification来实现,有关于UILocalNotification的介绍我们可以在其框架中可见。

// In iOS 8.0 and later, your application must register for user notifications using -[UIApplication registerUserNotificationSettings:] before being able to schedule and present UILocalNotifications
NS_CLASS_DEPRECATED_IOS(4_0, 10_0, "Use UserNotifications Framework's UNNotificationRequest") __TVOS_PROHIBITED
@interface UILocalNotification : NSObject<NSCopying, NSCoding>

在官方的解释中指出了UILocalNotification应该如何使用:在iOS8.0及更高的版本中,你的应用程序如果想要显示通知就必须使用-[UIApplication registerUserNotificationSettings:]注册用户通知

那么到此为止,我们关于本地推送的任务只需要两步就可以搞定了:

  1. 使用-[UIApplication registerUserNotificationSettings:]注册通知;
  2. 实现推送通知内容

1. 使用-[UIApplication registerUserNotificationSettings:]注册通知

注册通知的位置可以随意,只要步骤2之前就可以了。不过习惯性我们都会讲注册通知一类的放在程序启动的时候,即放在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions函数中。

在上述的官方解释中提到了注册通知是要使用-[UIApplication registerUserNotificationSettings:]来实现的,又因为其是个实例方法(-方法),故应使用UIApplication的实例对象调用该方法。

[[UIApplication sharedApplication] registerUserNotificationSettings:<#(nonnull UIUserNotificationSettings *)#>];

函数调用出来了,问题来了,这里调用的-registerUserNotificationSettings:这个函数还需要一个UIUserNotificationSettings类型的参数,我们来查看一下这个类。

@interface UIUserNotificationSettings : NSObject

// categories may be nil or an empty set if custom user notification actions will not be used
+ (instancetype)settingsForTypes:(UIUserNotificationType)types
                      categories:(nullable NSSet<UIUserNotificationCategory *> *)categories; // instances of UIUserNotificationCategory

@property (nonatomic, readonly) UIUserNotificationType types;

// The set of UIUserNotificationCategory objects that describe the actions to show when a user notification is presented
@property (nullable, nonatomic, copy, readonly) NSSet<UIUserNotificationCategory *> *categories;

@end

UIUserNotificationSettings类继承自NSObject,有一个类方法(+方法)用以初始化,此方法中包含了两个参数types和categories。

  1. types: 这个参数是一个UIUserNotificationType的枚举,如下所示:
typedef NS_OPTIONS(NSUInteger, UIUserNotificationType) {
    UIUserNotificationTypeNone    = 0,      // the application may not present any UI upon a notification being received
    UIUserNotificationTypeBadge   = 1 << 0, // the application may badge its icon upon a notification being received
    UIUserNotificationTypeSound   = 1 << 1, // the application may play a sound upon a notification being received
    UIUserNotificationTypeAlert   = 1 << 2, // the application may display an alert upon a notification being received
} NS_ENUM_DEPRECATED_IOS(8_0, 10_0, "Use UserNotifications Framework's UNAuthorizationOptions") __TVOS_PROHIBITED;

其具体意思就是说当应用程序收到通知的时候是否要更改显示程序角标、是否播放声音、是否弹框提醒等。

  1. categories: 这个参数在类方法的说明中就已经说明了,如果不适用自定义用户通知操作,可以设为nil

到这里推送的注册代码就已经可以写出来了:

// 此种通知只适用于iOS8.0及更高版本,故加个判断
if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        // 设置通知类型
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
        // 授权通知
        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    }

2. 实现推送通知内容

要使用UILocalNotification实现推送功能,我们首先可以查看一下该类的组成:

@interface UILocalNotification : NSObject<NSCopying, NSCoding>

// 初始化方法
- (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. for an egg timer).
// pass a time zone to interpret fireDate as a wall time to be adjusted automatically upon time zone changes (e.g. for an alarm clock).
// 推送时间所属时区的设置
@property(nullable, nonatomic,copy) NSTimeZone *timeZone;

// 重复时间
@property(nonatomic) NSCalendarUnit repeatInterval;      // 0 means don't repeat
@property(nullable, nonatomic,copy) NSCalendar *repeatCalendar;

// location-based scheduling

// set a CLRegion object to trigger the notification when the user enters or leaves a geographic region, depending upon the properties set on the CLRegion object itself. registering multiple UILocalNotifications with different regions containing the same identifier will result in undefined behavior. the number of region-triggered UILocalNotifications that may be registered at any one time is internally limited. in order to use region-triggered notifications, applications must have "when-in-use" authorization through CoreLocation. see the CoreLocation documentation for more information.
@property(nullable, nonatomic,copy) CLRegion *region NS_AVAILABLE_IOS(8_0);

// when YES, the notification will only fire one time. when NO, the notification will fire every time the region is entered or exited (depending upon the CLRegion object's configuration). default is YES.
@property(nonatomic,assign) BOOL regionTriggersOnce NS_AVAILABLE_IOS(8_0);

// alerts
// 弹出内容
@property(nullable, nonatomic,copy) NSString *alertBody;      // defaults to nil. pass a string or localized string key to show an alert
@property(nonatomic) BOOL hasAction;                // defaults to YES. pass NO to hide launching button/slider
@property(nullable, nonatomic,copy) NSString *alertAction;    // used in UIAlert button or 'slide to unlock...' slider in place of unlock
@property(nullable, nonatomic,copy) NSString *alertLaunchImage;   // used as the launch image (UILaunchImageFile) when launch button is tapped
@property(nullable, nonatomic,copy) NSString *alertTitle NS_AVAILABLE_IOS(8_2);  // defaults to nil. pass a string or localized string key

// sound
@property(nullable, nonatomic,copy) NSString *soundName;      // name of resource in app's bundle to play or UILocalNotificationDefaultSoundName

// badge
@property(nonatomic) NSInteger applicationIconBadgeNumber;  // 0 means no change. defaults to 0

// user info
@property(nullable, nonatomic,copy) NSDictionary *userInfo;   // throws if contains non-property list types

// category identifer of the local notification, as set on a UIUserNotificationCategory and passed to +[UIUserNotificationSettings settingsForTypes:categories:]
@property (nullable, nonatomic, copy) NSString *category NS_AVAILABLE_IOS(8_0);

@end

该类中包含了两个初始化方法- init- initWithCoder:以及很多的成员变量,这些成员变量就是发送通知的一些设置。关于部分成员变量的作用我直接在上面的代码中标注了(有些英文标注很清楚,就此略过)。下面就可以直接创建通知。

            // 创建通知
            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
            // 设置通知的必选参数
            // 设置通知显示的内容
            localNotification.alertBody = @"我来找你咯";
            // 设置通知发送的时间(这里设置的是当前时间延迟10s发送,创建通知我是放在按钮点击事件中了,点击之后,按home键等待10s即可收到推送)
            localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
            // 解锁滑动时的事件
            localNotification.alertAction = @"磨蹭啥呢";
            // 收到推送通知时APP icon角标,这里如果设置了,那么在应用程序即将启动的时候要记得把角标清空
            localNotification.applicationIconBadgeNumber = 1;
            // 推送是带有声音提醒的,设置默认的字段为 UILocalNotificationDefaultSoundName
            localNotification.soundName = UILocalNotificationDefaultSoundName;
            // 发送通知
            // 方式一:根据通知的发送时间(fireDate)发送通知
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
            // 方式二:立即发送通知
//            [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];

推送创建中还有很多参数,比如推送消息中包含图片等等,可以没事自己尝试一下,我这里只是搞了个最简单的。

总结

关于UILocalNotification实现本地推送的介绍就完了。我介绍的时候并不是直接告诉你应该怎么使用,而是告诉你应该怎么样才能更好的去学习一个新的类(东西),并不是看看别人怎么用的,然后自己拿过来直接使用就OK了,那样是不行的。

授人以鱼不如授人以渔。在你碰到一个新东西的时候,并不是要着急着去网上找关于这个东西的使用方法及其介绍,相反的我们可以自己通过查看其英文注释(我英语很差,但是需要耐着性子慢慢看,遇到不认识的单词谷歌一下,慢慢的你就能看懂咯)或者了解类的构造等各种方法来深入剖析其应该怎么使用以及其功能等等。

我认为我就是在一本正经的胡说八道 🤣🤣🤣

友情链接:iOS10 本地推送 UNUserNotificationCenter

相关文章

网友评论

    本文标题:iOS8 本地推送 UILocalNotification

    本文链接:https://www.haomeiwen.com/subject/oampmftx.html