Use of undeclared type UNAuthorizationOptions

2020-07-02 09:38发布

问题:

I am trying to use Firebase to handle push notifications. I have installed Firebase pod ('Firebase/Core' and 'FirebaseMessaging' pods).

And after I imported Firebase to the project

import Firebase

I have configured the Firebase app like this( code is copied from official docs ):

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
-> Bool {FIRApp.configure() }

After that I've tried to use this code ( code is copied from official docs ):

if #available(iOS 10.0, *) {
            let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_,_ in })

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

But I got the error from the title which says:

Use of undeclared type UNAuthorizationOptions

also I am having the same error related to the UNUserNotificationCenter class.

I am using Swift 2.2 and Xcode 7.3.1

What is the cause of this error?

回答1:

UserNotifications.framework is available from iOS 10 and you are working with Xcode 7.3 means with iOS 9 and lower, So there is no need for you to add that if #available(iOS 10.0, *) {, write only else part directly and register remote notifications.

let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()


回答2:

you need to import UserNotifications before calling those framework. And what Nirav D said is true, it is a new framework in iOS 10, should also remember to select the correct deployment target.