ios - 如何从 didRegisterForRemoteNotificationsWithDeviceToken 函数 ios swift 3 中删除几乎匹配的可选要求警告?

标签 ios swift push-notification swift3 xcode8

自从我将 xcode 更新为 xcode 8 后,我收到了这个警告:

实例方法

application(:didRegisterForRemoteNotificationsWithDeviceToken:)' nearly matches optional requirement 'application(:didRegisterForRemoteNotificationsWithDeviceToken:)' of protocol 'UIApplicationDelegate

Xcode 要求我通过将此函数设为私有(private)来消除此警告,但当我这样做时,该函数从未被调用(它没有以任何一种方式被调用)。

我尝试删除函数然后让自动完成填充它但没有任何效果。

这是有警告的函数:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    //
}

这是我完整的 appDelegate 文件:

@UIApplicationMain
class AppDelegate: UIResponder,UIApplicationDelegate,UNUserNotificationCenterDelegate,CLLocationManagerDelegate {

    var window: UIWindow?
    var locationManager:CLLocationManager?
    var coordinate: CLLocationCoordinate2D?
    func locationManagerStart() {

        if locationManager == nil {
            print("init locationManager")
            locationManager = CLLocationManager()
            locationManager!.delegate = self
            locationManager!.desiredAccuracy = kCLLocationAccuracyBest
            locationManager!.requestWhenInUseAuthorization()
        }

        print("have location manager")
        locationManager!.startUpdatingLocation()
    }

    func locationManagerStop() {
        locationManager!.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //
        let newLocation = locations.first!
        coordinate = newLocation.coordinate
        print("location updated")
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        registerForPushNotifications(application)

        return true
    }
    func registerForPushNotifications(_: UIApplication) {

        if #available(iOS 10.0, *){
            UNUserNotificationCenter.current().delegate = self

            UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
                if (granted)
                {
                    UIApplication.shared.registerForRemoteNotifications()
                }
                else{
                    //Do stuff if unsuccessful...
                }
            })
        }
        else{
        }
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

        print("I am not available in simulator \(error)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print(userInfo)
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var applicationDocumentsDirectory: URL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "com.youcode.Hebr" in the application's documents Application Support directory.
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls[urls.count-1]
    }()

    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = Bundle.main.url(forResource: "Hebr", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()

    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }

        return coordinator
    }()

    lazy var managedObjectContext: NSManagedObjectContext = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }
}

最佳答案

经过数周的搜索终于解决了! 问题是我有一个名为“Data”的类,它在 xcode 7 中没有出现任何错误,但是每当我将它添加到 xcode 8 中时,app delegate 中的 registerForNotification 函数都会出现此错误! 很奇怪,但最终通过更改 Data 类的名称解决了。

关于ios - 如何从 didRegisterForRemoteNotificationsWithDeviceToken 函数 ios swift 3 中删除几乎匹配的可选要求警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674641/

相关文章:

ios - App Store 上传因推送权利问题而被拒绝

android - PhoneGap PushPlugin 注册 ID

objective-c - 调用 dismissPopoverAnimated 或在弹出窗口外单击一次时,弹出窗口不会被关闭

ios - 更改后获取原始 View 高度

ios - 未在不同线程上调用委托(delegate)

ios - React native 全新安装 ReferenceError : Unknown plugin "transform-runtime" specified

swift - Swift 中的测试驱动开发

ios - 推送通知的证书和私钥

ios - : tableView. cellForRow 和 dataSource.cellForRowAtIndexPath 之间的区别

swift - XCUITest如何获取SkyFloatingLabelTextField中 float 标题的内容?