问题
I tried to convert my objective C AppDelegate to Swift AppDelegate. So I deleted the main.m file and Converted all the AppDelegate code to swift. I tried to run the project, then this error occurs.
Cannot find protocol declaration for 'UNUserNotificationCenterDelegate'
In the -Swift.h file they generate, this is the delegate they showed
- (void)userNotificationCenter:(UNUserNotificationCenter * _Nonnull)center willPresentNotification:(UNNotification * _Nonnull)notification withCompletionHandler:(void (^ _Nonnull)(UNNotificationPresentationOptions))completionHandler SWIFT_AVAILABILITY(ios,introduced=10.0);
This is how I have written
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
handleNotification(notification.request.content.userInfo)
}
Please help me get what is the issue am facing.
I tried, cleaning, restarting Xcode and restarting my Mac. Am using Swift 3.2.
This is my -Swift.h file error
If I comment the delegates, there are no errors.
回答1:
Strange fix but by importing #import in my bridging header the issue was resolved.
回答2:
This is how you need to proceed
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
registerForPushNotification()
return true
}
/**Register for push notification*/
func registerForPushNotification() {
let userNotification = UNUserNotificationCenter.current()
userNotification.delegate = self
userNotification.requestAuthorization(options: [.sound, .badge, .alert]) { (status, error) in
if error == nil {
DispatchQueue.main.async { // From iOS 10 onwards we need to call pushNotification registration method in main thread.
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
}
// MARK: - UNUserNotificationCenterDelegate methods
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound, .badge, .alert])
}
}
Thanks.
回答3:
You need to import following framework: import UserNotifications
来源:https://stackoverflow.com/questions/49429537/cannot-find-protocol-declaration-for-unusernotificationcenterdelegate-in-swif