ios - 如何在应用程序中显示 apns token ?在 swift 4

标签 ios swift function

如何在appdelegate中使用 View Controller 中的函数?在 Swift 4 中。

let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController") as! ViewController

viewController.setapnsText(token: deviceTokenString)
public func setapnsText(token: String) -> Void {
            apnsToken.text=token
}

我试过了,但不起作用。

最佳答案

只有当用户拥有/授予您的应用推送通知权限时,您才能在每次启动时接收设备 token 。此外,这通常可以且最容易地在 AppDelegate 中捕获。

因此,在我的示例中,我保存到 UserDefaults(不推荐)和核心数据(更推荐,因为如果您为应用程序启用本地加密,则可以利用本地加密)。

您像这样请求授权,对于一个旨在在 iOS 10 + 上运行并要求在启动时推送通知的应用程序:

class AppDelegate: UIResponder, UIApplicationDelegate {


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

        notificationHandler(application)
        return true

    }


    func notificationHandler(_ application: UIApplication) {
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.getNotificationSettings(){ (settings) in
                switch settings.authorizationStatus {
                case .authorized:
                    print("Authorized Push Notifications by User")
                    self.registerPushNotifications()
                case .denied:
                    print("show user a view explaining why it's better to enable")
                    self.registerPushNotifications()
                case .notDetermined:
                    self.requestPushNotifications(center: center, { (granted) in
                        if granted {
                            self.registerPushNotifications()
                            return
                        }
                        print("User did not grant Remote Notifications Authorizations")
                    })
                }
            }
        } else {
            print("App does not meet minimum OS Requirements")
            return
        }
    }

    fileprivate func requestPushNotifications(center: UNUserNotificationCenter,_ result: @escaping(Bool)->Void) {
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
            if error != nil {
                print("Could not request Authorization for Notifications - Yet is undetermined")
            } else {
                result(granted)
            }
        }
    }

    func registerPushNotifications() {
           if #available(iOS 10.0, *) {

               UIApplication.shared.registerForRemoteNotifications()

            } else {
                print("App does not meet base OS requirements")
            }
     }

     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
            UserDefaults.standard.set(deviceTokenString, forKey: "devicetoken")
            coreDataManager.saveDeviceToken(deviceTokenString)
      }

}

最终,如果您只想在应用程序中的其他时刻请求此操作,则可以扩展 NSObject,因为它是 AppDelegateUIViewController 的父类(super class) (无论如何,它是所有 Controller 类型类的根类。

class AppDelegate: UIResponder, UIApplicationDelegate {


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

        notificationHandler(application)
        return true

    }

     func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
            UserDefaults.standard.set(deviceTokenString, forKey: "devicetoken")
            coreDataManager.saveDeviceToken(deviceTokenString)
      }

}

extension NSObject {

    func notificationHandler(_ application: UIApplication) {
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.getNotificationSettings(){ (settings) in
                switch settings.authorizationStatus {
                case .authorized:
                    print("Authorized Push Notifications by User")
                    self.registerPushNotifications()
                case .denied:
                    print("show user a view explaining why it's better to enable")
                    self.registerPushNotifications()
                case .notDetermined:
                    self.requestPushNotifications(center: center, { (granted) in
                        if granted {
                            self.registerPushNotifications()
                            return
                        }
                        print("User did not grant Remote Notifications Authorizations")
                    })
                }
            }
        } else {
            print("App does not meet minimum OS Requirements")
            return
        }
    }

    fileprivate func requestPushNotifications(center: UNUserNotificationCenter,_ result: @escaping(Bool)->Void) {
        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
            if error != nil {
                print("Could not request Authorization for Notifications - Yet is undetermined")
            } else {
                result(granted)
            }
        }
    }

    func registerPushNotifications() {
        if #available(iOS 10.0, *) {

            UIApplication.shared.registerForRemoteNotifications()

        } else {
            print("App does not meet base OS requirements")
        }
     }

}

然后您可以在按钮的链接方法中调用它,如下所示:

class SomeController : UIViewController {

   override viewDidLoad() {
      super.viewDidLoad()
   }

   func requestNotificationsAuthorization() {
      notificationHandler(UIApplication.current)
   }

}

关于ios - 如何在应用程序中显示 apns token ?在 swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45463543/

相关文章:

ios - 跟踪和更改 UITextView 中文本的颜色

ios - 在运行时使用按钮更改应用程序语言

ios - XCode 9 : Module compiled with Swift 3. 0.2 无法在 Swift 3.2 中导入

postgresql - 如何从 PostgreSQL 中的函数访问外部作用域变量?

ios - 渐进式应用程序不再支持 Google OAuth?

ios - 如何让按钮阴影与 Swift 4.2 一起使用?

objective-c - 使用 spritekit,如何在横向卷轴游戏中实现滚动、随机倾斜的地板?

ios - Swift 中的 Mamaral 入门库

c - char* ft_name(args) 是否等同于 c 中的 char *ft_name(args)?

javascript - JS - 使用 "new"和将对象作为上下文传递给构造函数有什么区别