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

Posted

技术标签:

【中文标题】如何从 didRegisterForRemoteNotificationsWithDeviceToken 函数 ios swift 3 中删除几乎匹配的可选要求警告?【英文标题】:How to remove the nearly matches optional requirement warning from didRegisterForRemoteNotificationsWithDeviceToken function ios swift 3? 【发布时间】:2016-11-18 10:25:50 【问题描述】:

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

实例方法

应用程序(:didRegisterForRemoteNotificationsWithDeviceToken:)' 几乎符合可选要求 'application(:didRegisterForRemoteNotificationsWithDeviceToken:)' 的 协议'UIApplicationDelegate

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

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

这是有警告的函数:

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()
            
        
    

【问题讨论】:

【参考方案1】:

经过数周的搜索终于解决了! 问题是我有一个名为“Data”的类,它在 xcode 7 中没有出错,但是每当我在 xcode 8 中添加它时,应用程序委托中的 registerForNotification 函数都会出错! 很奇怪,但最终通过更改数据类的名称来解决。

【讨论】:

您也可以将符合协议的函数中的参数类型更改为“Foundation.Data”【参考方案2】:

在 Swift 3.0 中,第一个参数名称已更改。我认为您应该在函数的第一个参数中添加 下划线 _

在每种情况下都将_ application: 而不是application: 作为第一个参数的名称。

例如;

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


您也可以查看this link 了解更多信息

【讨论】:

好的,请将您的 appDelegate 文件完整分享给我 并检查您所有的 appDelegate 函数是否有下划线?或者您可以尝试自动完成所有 appDelegate 功能。我认为您可能在某些功能中忘记了下划线。

以上是关于如何从 didRegisterForRemoteNotificationsWithDeviceToken 函数 ios swift 3 中删除几乎匹配的可选要求警告?的主要内容,如果未能解决你的问题,请参考以下文章

如何将数据从回收器适配器发送到片段 |如何从 recyclerview 适配器调用片段函数

如何从 Firebase 获取所有设备令牌?

如何直接从类调用从接口继承的方法?

如何从服务器获取和设置 android 中的 API(从服务器获取 int 值)?如何绑定和实现这个

如何从Mac从android studio中的fabric注销? [复制]

如何从设备中获取 PDF 文件以便能够从我的应用程序中上传?