内容
-
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
}
}