[iOS10]新しいフレームワークを利用してみよう! – 1 –

前回は、uniSwfに使用する素材の外部化についてご紹介しました。
今回は、iOS10で新規に追加されたフレームワークについてご紹介したいと思います。

ご紹介するフレームワークは、「UserNotificationsフレームワーク」です。
このフレームワークを利用してローカル通知を行うアプリを作成してみたいと思います。
※ローカル通知とは、事前にアプリ内で設定した内容が、「アプリを起動していない」もしくは、
「アプリがバックグラウンド状態」でも、指定した時刻にアプリへ通知することができる機能のことです。

ただし、iOS9以前からローカル通知は存在していました。
「UIKitフレームワーク」の「UILocalNotification」というクラスを利用して実現していましたが、
今回、iOS10で「Deprecated(非推奨)」になり、そのクラスは利用できなくなりました。

厳密にいうと、「Deprecated」なので、すぐ利用できなくなるということはありません。
「UILocalNotification」クラスが削除されるまで、利用することができます。
ただし、Appleの都合のよいタイミングで、いきなり削除されるので、予期せぬタイミングで
利用することができなくなる可能性があります。

それでは、ここで「UserNotificationsフレームワーク」で追加された機能を簡単にご紹介しておきます。
・アプリが起動中である場合でも、画面上に通知できるようになった
 ※iOS9以前からある「UILocalNotification」というクラスでは、アプリを起動していない」
  もしくは、「アプリがバックグラウンド状態」でのみ通知

・通知エリア内にカレンダーや地図を表示できるようになった

今後のことを考えて、「UIKitフレームワーク」の「UILocalNotification」クラスでローカル通知を
行っているアプリは、「UserNotificationsフレームワーク」に置き換える必要があります。

それでは実際に「UserNotificationsフレームワーク」を利用したサンプルアプリを作成してみましょう。

<サンプルアプリの作成方法>
【前提条件】
 ・開発環境は、「Xcode 8 beta版」であること
 
【手順1】
 新規にプロジェクトを作成します。
 
 
 
【手順2】
 画面を作成します。
 今回は、「登録」ボタンタップで、ローカル通知を設定します。
 
 
 
【手順3】
 「UserNotifications.framework」を追加します。
 
 

【手順4】
 「AppDelegate.h/m」にローカル通知の初期設定を行います。
 
 ・AppDelegate.h

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
//ヘッダをインポートする
#import <UserNotifications/UserNotifications.h>

//UserNotificationsのDelegateを設定する
@interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong) NSPersistentContainer *persistentContainer;
- (void)saveContext;
@end

 
 ・AppDelegate.m
 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //NotificationCenterのインスタンスを作成する
    UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
    
    //Delegateを設定する
    notificationCenter.delegate = self;
    
    //通知のタイプを設定する
    //今回は、音とアラートを設定
    [notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionSound|UNAuthorizationOptionAlert
                                      completionHandler:^(BOOL granted, NSError * _Nullable error) {
    }];
    
    return YES;
}

 
【手順5】
 「ViewController.m」ファイルに「登録」ボタンタップ時の処理を追加します。
 実際にローカル通知を設定します。

- (IBAction)buttonClick:(id)sender
{
    NSMutableArray *identifiers = [NSMutableArray array];
    
    __block NSArray *requestList = [NSArray array];
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    /***********************************************/
    //ローカル通知を設定する前に、残っている通知を削除する
    
    //通知リクエストを取得する
    [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
        requestList = requests;
        dispatch_semaphore_signal(semaphore);
    }];
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    //通知を削除するために通知リクエストのidentifierを取得する
    for (UNNotificationRequest *notification in requestList) {
        //identifierを保持する
        [identifiers addObject:notification.identifier];
    }
    
    if(0 != identifiers.count) { {
    }
        //通知リクエストを削除する
        [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:identifiers];
    
    /***********************************************/

    /***********************************************/
    //通知する日付を作成する
    
    //現在日付を取得する
    NSDate *date = [NSDate date];
    
    // 年月日をとりだす
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth  | NSCalendarUnitDay |
                                                                             NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
    //現在日付の1分後に設定する
    components.minute += 1;
    components.second  = 0;
    /***********************************************/
    
    /***********************************************/
    //通知を設定する
    
    //通知する日付を指定する
    UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
    
    //ローカル通知時に表示するメッセージを作成する
    UNMutableNotificationContent *notification = [[UNMutableNotificationContent alloc] init];
    notification.body = @"ローカル通知 サンプル";
    notification.sound = [UNNotificationSound defaultSound];
    /***********************************************/

    /***********************************************/
    //通知リクエストを作成する
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"1234567890" content:notification trigger:trigger];
    
    //通知を設定する
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request
                                                           withCompletionHandler:^(NSError * _Nullable error) {
                                                           }];
    /***********************************************/

}

お疲れさまでした。
それでは、実際に作成したアプリを動かしてみましょう。
※iOS10の端末がないので、シミュレータで行いました。

【手順1】
 アプリを起動し、通知を許可します。
 
 

【手順2】
 「登録」ボタンをタップします。
 
 

【手順3】
 アプリをバックグラウンドにし、指定した時刻まで待ちます。
 
 

【手順4】
 指定した時間になると通知がきます。
 
 

ローカル通知を利用すると、スケジュール/アラーム通知や、アプリの起動を
促すメッセージを表示することができるので、とても便利です。

「UserNotificationsフレームワーク」にはまだ、いろいろな機能があるので、
次回以降、またご紹介させていただきたいと思います。
※「UserNotificationsUI」という フレームワークがありますので、
 併せてご紹介していきたいと思います。

これで、「新しいフレームワークを利用してみよう!」は終了となります。

皆さんも、ぜひiOS10でローカル通知を利用してみてください。

最後までご覧いただき、ありがとうございました。


弊社では全国各地の請負い(ご自宅)で作業協力頂ける、フリーランスエンジニアの方を常時探しております。
ご興味ある方は、お気軽にお問い合わせ下さい。


コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*