在自己的自定义类上处理UIApplicationDelegate回调而不是AppDelegate类

时间:2017-10-02 01:27:05

标签: ios swift swift3

我正在尝试通过方法registerForPushNotification()注册推送通知,并希望处理这个所述类而不是AppDelegate类的所有委托回调。不知何故,在实施代理UIApplicationDelegate之后,我仍然没有得到回调。有办法吗?

public class PushNotification: NSObject {
  public var window: UIWindow?
  var token: Data = Data()
  var userInfo: [AnyHashable : Any]!


  @objc public static func registerForPushNotification() {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
      (granted, error) in
      print("Permission granted: \(granted)")
    }
    UIApplication.shared.registerForRemoteNotifications()
  }
}

extension PushNotification : UIApplicationDelegate {
  public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { data -> String in
      return String(format: "%02.2hhx", data)
    }

    let token = tokenParts.joined()
    print("Device Token: \(token)")
  }

  public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")
  }
  public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("notification received")
    self.userInfo = userInfo

    completionHandler(.noData)
  }
}

3 个答案:

答案 0 :(得分:0)

即使采用UIApplicationDelegate协议,我也不会认为您的自定义类实例会收到通知。

协议中定义的回调在已注册的应用程序代理上调用;即delegate UIApplication.shared属性引用的对象(反过来,它是表示正在运行的应用程序的对象)。

通过在main.m中实例化name指定的类(对于Objective-C代码),app delegate在启动时设置自动

@import UIKit;
#import "AppDelegate.h"

int main(int argc, char * argv[]) {

    @autoreleasepool {
        return UIApplicationMain(
            argc, 
            argv, 
            nil, 
            NSStringFromClass([AppDelegate class]) // <-- THIS
        ); 
    }
}

...或标有@UIApplicationMain(在Swift代码中):

import UIKit

@UIApplicationMain // <-- THIS
class AppDelegate: UIResponder, UIApplicationDelegate { 

答案 1 :(得分:0)

UIApplicationDelegate只是AppDelegate必须符合的一组协议。

需要显式指定对象的委托,以便对象与其进行交互。 就像您将表的委托(例如)分配为tableView.delegate = self一样,默认情况下,应用程序的委托被分配给AppDelegate类。

由于AppDelegate已经处理了所有内容,您可以扩展它并在其中包含您自己的功能,或者您可以创建自定义委托,然后让它处理AppDelegate将承担的所有责任。没有办法将应用程序回调拆分为多个代理。

但是,如果您仍想在自己的班级中处理来自远程通知的回调,您可以做的是 -

  1. 添加处理AppDelegate中的远程通知的功能
  2. 让每个功能发布通知
  3. 在您自己的班级处理所有此类通知

答案 2 :(得分:0)

为此,要做到这一点,你必须做3件事!

  • 采用协议
  • 符合协议要求
  • 设置代理。

但是你没有在任何地方设置代表(即你没有做与UIApplication.delegate = self类似的事情,所以没有你赢得回调!

如果您想做这样的事情,我建议您关注this hack。请务必阅读以下评论!