我正在使用 Xcode 9.2、Swift 4.0 编写 VoIP 应用程序,最低 iOS 版本为 10.3。即使 iPhone 处于睡眠模式(就像 WhatsApp 或 Viber 一样),我也想接听来电。我已经知道我必须为此使用 CallKit。但我不知道如何正确接收推送通知。我的意思是,我有两种接收方式。首先在 AppDelegate.swift 中,请看(这个方法有效):
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Getting permissions for Notifications
//222
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
}
application.registerForRemoteNotifications()
//222
return true
}
//For PUSH Notifications settings
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("NOTIFICATION ERROR: \(error)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let pushToken = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}).lowercased()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Receiving call?
}
}
但是,无论我在做什么,如果 iPhone 处于睡眠状态,它都不会触发来电。最近我看到还有另一种接收推送通知的方法。敬请期待:
import UIKit
import CallKit
import PushKit
class ViewController: UIViewController, CXProviderDelegate, PKPushRegistryDelegate {
override func viewDidLoad() {
let registry = PKPushRegistry(queue: nil)
registry.delegate = self
registry.desiredPushTypes = [PKPushType.voIP]
}
func providerDidReset(_ provider: CXProvider) {
}
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
action.fulfill()
}
func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
print(pushCredentials.token.map { String(format: "%02.2hhx", $0) }.joined())
}
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) {
// Receive call?
}
}
问题是在第一种方法中我有这个 PUSH 令牌:9bcf73ac3d6a68be07c26d8b6a972f5b716cd5308f1a19048b62d19b9b8d4bd1
第二种方法返回我这个 PUSH 令牌:1e40fafb2963161b1bcf1bdde00d625a879c6934e19e2fb32f62b1c9272e956f
而且他们是不平等的!怎么会这样?所以,主要问题是:如何接收 PUSH 通知,AppDelegate 和 PushKit 方法有什么区别,哪个令牌是正确的?
感谢您的任何帮助!