■iOS: アプリにPush機能を実装
Xcodeのプロジェクトの「Settings & Capabilities」で「+Capabilities」をクリックし、一覧に表示される「Background Modes」をダブルクリックで選択する
その後、画面に表示される「Remote notification」にチェックを入れる
以下の記事に参考画面があるが、当時からUIは変更されている
You've implemented -[ application: didReceiveRemoteNotification: fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist.の解決法 - ゆーじのUnity開発日記
http://unity-yuji.xyz/youve-implemented-applicationdidreceiveremotenotification-remote-notification-...
ストーリーボードにパーツを配置(オートレイアウトなどは、必要に応じて設定する)
Device Token ... Lavel
[ ] ... Text Field(一行入力欄)
ViewController.swift
//
// ViewController.swift
// pushtest1
//
// Created by refirio on 2019/12/13.
// Copyright (C) 2019 refirio. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var deviceTokenTextField: UITextField!
let ap = UIApplication.shared.delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
ap.mainView = self
// アプリを起動したらバッジの数字を消す
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
AppDelegate.swift
//
// AppDelegate.swift
// pushtest1
//
// Created by refirio on 2019/12/13.
// Copyright (C) 2019 refirio. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var mainView : ViewController!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForPushNotifications()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// プッシュ通知の許可を得られたとき
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
print("Device Token: \(token)")
self.mainView.deviceTokenTextField.text = token
}
// プッシュ通知の許可を得られなかったとき
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register for remote notifications with error: \(error)")
}
/*
// アプリ起動中に通知を受信する
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Received message")
}
*/
// アプリがフォアグラウンドの際に通知を受け取ったとき
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// 通知センターのバナーを表示する
completionHandler([.alert, .sound]) // 通知バナー表示、通知音の再生を指定
}
// プッシュ通知の許可を得る
func registerForPushNotifications() {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound,.badge]) { (Bool, Error) in
print("Permission granted: \(Bool)")
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
※plistの編集は不要だった
※CocoaPodsのインストールは不要だった
■動作確認
アプリを実行すると、画面内のテキストフィールドに文字列(デバイストークン)が表示される
この文字列をもとに、サーバサイドプログラムからプッシュを送信する
※エミュレータではプッシュを受け取れないので、実機で実行する
※実行すると「"pushtest1"は通知を送信します。よろしいですか?」のダイアログが表示されるので許可する
■MacアプリケーションのPusherから送信(デバッグ用)
MacにPusherをインストールすれば、そこからプッシュを送ることができる
https://github.com/noodlewerk/NWPusher/releases
インストールして起動する
証明書の選択欄があるが、ここにはキーチェーンアクセスに登録してあるPush通知の証明書が表示される
選択して「Reconnect」をクリックする。パスワードを求められたら、Macのログインパスワードを入力する
その下に送信先を入力する
ここにはデバイストークンを入力する
一番下のテキストエリアに、送信したい内容を入力する
以下のようにJSON形式で入力できる
{"aps":{"alert":"テスト1","badge":1,"sound":"default"}}
「Push」ボタンを押すとプッシュが送信される
■WindowsアプリケーションのPush Notificationsから送信(デバッグ用)
WindowsにPush Notificationsをインストールすれば、そこからプッシュを送ることができる
https://github.com/onmyway133/PushNotifications/releases
Push.Notifications-1.7.3-windows.msi をダウンロード
ダウンロードしてインストールし、起動する
p12ファイルでプッシュを送信する場合、
iOS → Authentication → CERTIFICATE
で「SELECT P12」をクリックし、p12ファイルを選択する
p8ファイルでプッシュを送信する場合、
iOS → Authentication → TOKEN
で「SELECT P8」をクリックし、p8ファイルを選択する
「Enter key id」と「Enter team id」にも必要情報を入力する
iOS → Body
で「Enter bundle id」にバンドルIDを入力する
で「Enter device token」にデバイストークンを入力する
iOS → Environment
は「Development SSL Certificate」としてプッシュ通知用の証明書を作成した場合は「Sandbox」のまま
「Production SSL Certificate」としてプッシュ通知用の証明書を作成した場合は「Production」に変更する
「Send」ボタンを押すとプッシュが送信される