local Notifications
でiOS 10
を開発しました。完璧に機能しています。しかし、ユーザーがlocal notifications
以上のバージョンを使用している場合、どのようにPush notification
およびiOS 9
をコーディングする必要がありますか。誰でも助けてくれますか?
以下はiOS 10
のコードです
import UIKit
import UserNotifications
@available(iOS 10.0, *)
class ViewController: UIViewController,UNUserNotificationCenterDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 10.0, *) {
//Seeking permission of the user to display app notifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge], completionHandler: {didAllow,Error in })
UNUserNotificationCenter.current().delegate = self
}
}
//To display notifications when app is running inforeground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound, .badge])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonPressed(_ sender: UIButton) {
if #available(iOS 10.0, *) {
//Setting content of the notification
let content = UNMutableNotificationContent()
content.title = "hello"
content.body = "notification pooped out"
content.badge = 1
//Setting time for notification trigger
let date = Date(timeIntervalSinceNow: 10)
var dateCompenents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateCompenents, repeats: false)
//Adding Request
let request = UNNotificationRequest(identifier: "timerdone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}
}
IOS 12:-グループ通知
threadIdentifier
UNMutableNotificationContent
を設定してグループ通知を作成します
ローカル通知グループを作成する
let content = UNMutableNotificationContent()
content.title = "Group Notifications"
content.body = "Body of notification"
content.threadIdentifier = "group-identifire"
リモート通知グループを作成するには、thread-id
ペイロード内
{
"aps" : {
"alert" : {
"title" : "Group Notifications",
"body" : "Body of notification"
}
"thread-id" : "group-identifire"
}
}
IOS 11:-また、iOS 11では次のコードを使用できます。プッシュおよびローカル通知での変更は一切必要ありません。
通知要求の作成
import UserNotifications
if #available(iOS 10.0, *) {
//iOS 10.0 and greater
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { granted, error in
DispatchQueue.main.async {
if granted {
UIApplication.shared.registerForRemoteNotifications()
}
else {
//Do stuff if unsuccessful...
}
}
})
}
else {
//iOS 9
let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
let setting = UIUserNotificationSettings(types: type, categories: nil)
UIApplication.shared.registerUserNotificationSettings(setting)
UIApplication.shared.registerForRemoteNotifications()
}
ローカル通知のスケジュール
if #available(iOS 10.0, *) {
//iOS 10 or above version
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Late wake up call"
content.body = "The early bird catches the worm, but the second mouse gets the cheese."
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default()
var dateComponents = DateComponents()
dateComponents.hour = 15
dateComponents.minute = 49
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
} else {
// ios 9
let notification = UILocalNotification()
notification.fireDate = NSDate(timeIntervalSinceNow: 5) as Date
notification.alertBody = "Hey you! Yeah you! Swipe to unlock!"
notification.alertAction = "be awesome!"
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.shared.scheduleLocalNotification(notification)
}
IApplicationDelegate
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(token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}
NUserNotificationCenterDelegate
IOS 10以降のバージョンでのみ利用可能
メソッドは、アプリケーションがフォアグラウンドにある場合にのみ、デリゲートで呼び出されます
次の方法でデフォルトのバナーを提示できます
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge,.alert,.sound])
}
このメソッドは、ユーザーがアプリケーションを開く、通知を閉じる、またはUNNotificationActionを選択することで通知に応答したときにデリゲートで呼び出されます
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
}
Swiftに対してこのクラスを作成しました。このクラスには、プッシュ通知と送信通知の許可を要求する機能があります。 iOS 9およびiOS 10以降で動作します。
import UIKit
import UserNotifications
class LocalNotification: NSObject, UNUserNotificationCenterDelegate {
class func registerForLocalNotification(on application:UIApplication) {
if (UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:)))) {
let notificationCategory:UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
notificationCategory.identifier = "NOTIFICATION_CATEGORY"
//registerting for the notification.
application.registerUserNotificationSettings(UIUserNotificationSettings(types:[.sound, .alert, .badge], categories: nil))
}
}
class func dispatchlocalNotification(with title: String, body: String, userInfo: [AnyHashable: Any]? = nil, at date:Date) {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.categoryIdentifier = "Fechou"
if let info = userInfo {
content.userInfo = info
}
content.sound = UNNotificationSound.default()
let comp = Calendar.current.dateComponents([.hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: comp, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
} else {
let notification = UILocalNotification()
notification.fireDate = date
notification.alertTitle = title
notification.alertBody = body
if let info = userInfo {
notification.userInfo = info
}
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.shared.scheduleLocalNotification(notification)
}
print("WILL DISPATCH LOCAL NOTIFICATION AT ", date)
}
}
使用法:
どこでも許可をリクエストできます:
LocalNotification.registerForLocalNotification(on: UIApplication.shared)
ローカル通知を送信するには:
LocalNotification.dispatchlocalNotification(with: "Notification Title for iOS10+", body: "This is the notification body, works on all versions", at: Date().addedBy(minutes: 2))
ヒント:
通知は、将来の任意の日付に起動するように設定できます。この例では、日付拡張を使用して、通知の起動までの将来の日付を分単位で取得します。これです:
extension Date {
func addedBy(minutes:Int) -> Date {
return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
}
}