はじめに
iOS10からNotificationのUIをカスタマイズできるようなので試してみました。
(タイトルとボディ部の上のエリアのみ)
完成イメージ
NotificationにWebViewを設置してみました。
開発環境は、XCode8.0
動作環境は、iOS10.0.1です。
動作イメージ
- Remindボタンを押下する
- 1秒後にNotificationが表示される(Local Notification)
- Notificationを下に引っ張るとカスタマイズしたUIが表示される
実装してみます
1. アプリ側の実装
(1) Notificationの利用許可ダイアログを表示
iOS10からの仕様変更分の記載です。
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert], completionHandler: { (granted, error) in
if error != nil {
print(error?.localizedDescription)
return
}
})
return true
}
}
(2) Local Notificationの登録
今回は、Remindボタンを押下すると、ローカル通知を登録するようにしました。
通知は、1秒後に発火します。
なお、カテゴリIDは、このあとContent Extensionで定義する
UNNotificationExtensionCategoryと一致している必要があります。
今回は、「remind」としました。
import UIKit
import UserNotifications
class ViewController: UIViewController {
@IBAction func onDidTappedRemind(_ sender: UIButton) {
addCategory()
addLocalNotification()
}
func addCategory() {
let category = UNNotificationCategory(identifier: "remind",
actions: [],
intentIdentifiers: [],
options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
}
func addLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "オススメ動画"
content.body = "『弱虫ペダル』放映中"
content.categoryIdentifier = "remind"
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 1,
repeats: false)
let request = UNNotificationRequest.init(identifier: "remind",
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
}
2. Content Extension側の実装
(1) Xcode の File > New > Targetを選択する
(2) Notification Contentを選択する
(3) Product名などを指定して Finishし、Activateを選択
アプリ側のProduct名と別の名前を定義しておきます。
(4) info.plistを設定する
UNNotificationExtensionCategoryは、
アプリ側で定義したカテゴリIDを設定しましょう。
今回の例では、「remind」です。
(5) レイアウト(MainInterface.storyboard)を定義する
今回は、WebViewのみを画面いっぱいに定義しました。
(6) WebViewを表示する
import UIKit
import UserNotifications
import UserNotificationsUI
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
}
func didReceive(_ notification: UNNotification) {
let requestURL = NSURL(string: "https://www.youtube.com/watch?v=C36DbikADzc")
let req = NSURLRequest(url: requestURL as! URL)
webView.loadRequest(req as URLRequest)
}
}
まとめ
NotificationのUIをカスタマイズするには、「Notification Content」を使いましょう。
UIはstoryboardで作成でき、AutoLayoutも利用できるので便利です。
今回は、静的Webページのみを表示しました。
通知をタップしたあと、動作再生ページを表示すると、
ダイレクトに再生できそうです。
Remote NotificationでもUIのカスタマイズはできるのでしょうか??
どなたかご存知の方がいらっしゃいましたら、ご教授頂ければと思います。
APNSの「category」と
Content Extensionのplistで定義した「UNNotificationExtensionCategory」を
揃えるとできるのかと思い、試行錯誤しましたが、ダメでした。。。(汗!)
以上です。