LoginSignup
1

More than 5 years have passed since last update.

通知の許可を要求する際のoptions引数について (User Notifications framework)

Last updated at Posted at 2017-07-27

内容

  • requestAuthorization(options:completionHandler:)のoptions引数にUNAuthorizationOptions型の配列を渡すとコンパイルエラーが出る
  • エラー内容:Cannot convert value of type '[UNAuthorizationOptions]' to expected argument type 'UNAuthorizationOptions'
  • 以下のような形で解決できたのでメモ

環境

  • Xcode: 8.3.3
  • Swift: 3.1

通知許可を処理するクラス

MyNotifications.swift
import Foundation
import UserNotifications

class MyNotifications: NSObject {
    /// 通知の許可ダイアログを表示させる
    ///
    /// - Parameter options: 通知の種類
    class func requestAuthorization(withOptions options: UNAuthorizationOptions...) {
        var optionSet: UNAuthorizationOptions = []
        for option in options {
            optionSet.insert(option)
        }

        UNUserNotificationCenter.current().requestAuthorization(options: optionSet) { (granted, error) in
            if error != nil {
                print("エラー")
                return
           }

            if granted {
                print("通知許可")
            } else {
                print("通知拒否")
            }
        }
    }
}

AppDelegate等で呼び出す

AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // アラート、バッジ、サウンドの許可を要求する
        MyNotifications.requestAuthorization(withOptions: .alert, .badge, .sound)

        return true
    }

}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1