Токен Pushkit не попадает на некоторые устройства iOS

Я реализовал PushKit. Я выполнил следующие шаги:

1.) https://stackoverflow.com/a/38184769/4970453

2.) https://stackoverflow.com/a/28562124

Я могу получить токен устройства didUpdatePushCredentials. работает в --> iPhone 5s, iPhone6 ​​Plus

didUpdatePushCredentials Не работает в --> iPhone6 ​​и iPhone7

Я использую одинаковые сертификаты и сборку для всех устройств. Не знаю точного вопроса. Если кто сталкивался с такой проблемой, поделитесь способами.

Мой код и ссылка на сертификат

код -> https://www.dropbox.com/sh/x2615t7xn8mavs3/AADbX5nBuF5_08YNPX8wI59ga?dl=0

cer -> https://www.dropbox.com/sh/70l4htj1c46emog/AABxBalaoN1JP22dQp8-mNXGa?dl=0

 Solution -----> I have changed Bundle identifier And create New certificate with New BundleId.

person Varinder Singh iPhone Dev    schedule 12.07.2017    source источник
comment
Вы проверяли интернет-соединение на этих устройствах?   -  person D4ttatraya    schedule 12.07.2017
comment
включите фоновый режим настроек voip в возможностях проекта, а также проверьте настройки push-уведомлений приложения в настройках устройства.   -  person MAhipal Singh    schedule 13.07.2017
comment
Изменение идентификатора пакета не кажется мне решением...   -  person rockdaswift    schedule 01.04.2019


Ответы (4)


Он должен работать на всех устройствах при правильной интеграции. для конкретного устройства ничего не изменилось.

Вы можете перекрестно проверить свои шаги.

Свифт

import UIKit
import PushKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,PKPushRegistryDelegate {

    var window: UIWindow?

    var isUserHasLoggedInWithApp: Bool = true
    var checkForIncomingCall: Bool = true
    var userIsHolding: Bool = true

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


        if #available(iOS 8.0, *){


            let viewAccept = UIMutableUserNotificationAction()
            viewAccept.identifier = "VIEW_ACCEPT"
            viewAccept.title = "Accept"
            viewAccept.activationMode = .Foreground
            viewAccept.destructive = false
            viewAccept.authenticationRequired =  false

            let viewDecline = UIMutableUserNotificationAction()
            viewDecline.identifier = "VIEW_DECLINE"
            viewDecline.title = "Decline"
            viewDecline.activationMode = .Background
            viewDecline.destructive = true
            viewDecline.authenticationRequired = false

            let INCOMINGCALL_CATEGORY = UIMutableUserNotificationCategory()
            INCOMINGCALL_CATEGORY.identifier = "INCOMINGCALL_CATEGORY"
            INCOMINGCALL_CATEGORY.setActions([viewAccept,viewDecline], forContext: .Default)

            if application.respondsToSelector("isRegisteredForRemoteNotifications")
            {
                let categories = NSSet(array: [INCOMINGCALL_CATEGORY])
                let types:UIUserNotificationType = ([.Alert, .Sound, .Badge])

                let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: categories as? Set<UIUserNotificationCategory>)

                application.registerUserNotificationSettings(settings)
                application.registerForRemoteNotifications()
            }

        }
        else{
            let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
            application.registerForRemoteNotificationTypes(types)
        }


        self.PushKitRegistration()

    return true
    }
    //MARK: - PushKitRegistration

    func PushKitRegistration()
    {

        let mainQueue = dispatch_get_main_queue()
        // Create a push registry object
        if #available(iOS 8.0, *) {

        let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue)

        // Set the registry's delegate to self

        voipRegistry.delegate = self

        // Set the push type to VoIP

        voipRegistry.desiredPushTypes = [PKPushTypeVoIP]

        } else {
        // Fallback on earlier versions
        }


    }


    @available(iOS 8.0, *)
    func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {
        // Register VoIP push token (a property of PKPushCredentials) with server

        let hexString : String = UnsafeBufferPointer<UInt8>(start: UnsafePointer(credentials.token.bytes),
        count: credentials.token.length).map { String(format: "%02x", $0) }.joinWithSeparator("")

        print(hexString)


    }


    @available(iOS 8.0, *)
    func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {

        // Process the received push

        // Below process is specific to schedule local notification once pushkit payload received

        var arrTemp = [NSObject : AnyObject]()
        arrTemp = payload.dictionaryPayload

        let dict : Dictionary <String, AnyObject> = arrTemp["aps"] as! Dictionary<String, AnyObject>


        if isUserHasLoggedInWithApp // Check this flag then only proceed
        {

            if UIApplication.sharedApplication().applicationState == UIApplicationState.Background || UIApplication.sharedApplication().applicationState == UIApplicationState.Inactive
            {

                if checkForIncomingCall // Check this flag to know incoming call or something else
                {

                    var strTitle : String = dict["alertTitle"] as? String ?? ""
                    let strBody : String = dict["alertBody"] as? String ?? ""
                    strTitle = strTitle + "\n" + strBody

                    let notificationIncomingCall = UILocalNotification()

                    notificationIncomingCall.fireDate = NSDate(timeIntervalSinceNow: 1)
                    notificationIncomingCall.alertBody =  strTitle
                    notificationIncomingCall.alertAction = "Open"
                    notificationIncomingCall.soundName = "SoundFile.mp3"
                    notificationIncomingCall.category = dict["category"] as? String ?? ""

                    //"As per payload you receive"
                    notificationIncomingCall.userInfo = ["key1": "Value1"  ,"key2": "Value2" ]


                    UIApplication.sharedApplication().scheduleLocalNotification(notificationIncomingCall)

                }
                else
                {
                    //  something else
                }

            }
        }


    }

    //MARK: - Local Notification Methods

    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification){

        // Your interactive local notification events will be called at this place

    }


}

Цель C

#import <UIKit/UIKit.h>
#import <PushKit/PushKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate,PKPushRegistryDelegate>
{
    PKPushRegistry *pushRegistry;
}

@property (strong, nonatomic) UIWindow *window;

@end

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


    pushRegistry = [[PKPushRegistry alloc] initWithQueue:dispatch_get_main_queue()];
    pushRegistry.delegate = self;
    pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];

    return YES;
}

#define PushKit Delegate Methods

- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type{
    if([credentials.token length] == 0) {
        NSLog(@"voip token NULL");
        return;
    }

    NSLog(@"PushCredentials: %@", credentials.token);
}

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type
{
    NSLog(@"didReceiveIncomingPushWithPayload");
}

https://github.com/hasyapanchasara/PushKit_SilentPushNotification

Обновленный ответ

https://drive.google.com/file/d/0B7ooURy3zGWKYW5PZE1aN2pObW8/view?usp=sharing

Обновленный ответ

Ниже приведены некоторые варианты устранения неполадок.

(1) Измените идентификатор com и повторите попытку.

(2) Сохраняйте код puhkit в делегате приложения

Я думаю, вы можете изменить идентификатор пакета и попробовать еще раз, он должен работать со всеми устройствами.

person Hasya    schedule 12.07.2017
comment
Вы можете заархивировать свой проект, только часть с кодом VOIP и указать URL-адрес диска в своем вопросе, чтобы любой мог скачать, найти проблему и решение. - person Hasya; 13.07.2017
comment
Почему вы не храните объект pushRegistry в файле .h? Также почему не в AppDelegate? Какой-либо причине ? - person Hasya; 13.07.2017
comment
Проверьте мой обновленный ответ, я внес некоторые изменения в ваш код, загрузите этот почтовый индекс и проверьте. - person Hasya; 13.07.2017

Убедитесь, что на странице сертификатов у вас включены push-уведомления в идентификаторе приложения. Также попробуйте использовать соединение 3G/4G. Возможно, конфигурация сети не позволяет устройству получить токен.

person rockdaswift    schedule 01.04.2019

Чтобы PushKit работало правильно, нам необходимо выполнить следующие шаги:

  1. Включить Push-уведомления в возможностях проекта
  2. Включить удаленные уведомления в фоновом режиме
  3. Подключить устройство к интернету
  4. Разрешить приложению получать push-уведомления

См. это пошаговое руководство.


Поскольку это происходит только для некоторых устройств, возможно, 3-й и 4-й шаги ответственны.

person D4ttatraya    schedule 12.07.2017

В моем случае я не получал токен VoIP на некоторых своих устройствах. ЖЕСТКИЙ СБРОС этих устройств решил мою проблему.

person ak_ninan    schedule 16.04.2018