如何发送推送通知以在线测试 iOS PushKit 集成? [英] How to send Push Notifications to test iOS PushKit integration online?

查看:23
本文介绍了如何发送推送通知以在线测试 iOS PushKit 集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了 PushKit.现在我想收到推送通知.由于我们有许多在线 APNS 服务接受设备令牌和 .pem 文件以发送远程通知,所以有没有办法在线获取推送通知?

解决方案

您可以创建自己的 php 文件.

来源

使用这个 simplepush.php 文件

$消息,'声音' =>'默认','徽章' =>0,);//将有效负载编码为 JSON$payload = json_encode($body);//构建二进制通知$msg = chr(0) .包('n', 32) .pack('H*', $deviceToken) .pack('n', strlen($payload)) .$有效载荷;//发送到服务器$result = fwrite($fp, $msg, strlen($msg));如果(!$结果)echo '消息未送达'.PHP_EOL;别的echo '消息发送成功'.PHP_EOL;//关闭与服务器的连接fclose($fp);

使用下面的命令创建pem文件并在上面的代码中使用

$ openssl x509 -in aps_development.cer -inform der -out PushCert.pem# 将 .p12 转换为 .pem.输入您的密码,它与您在创建 .p12 证书时提供的密码相同.PEM 密码短语也与 .p12 证书相同.$ openssl pkcs12 -nocerts -out PushKey1.pem -in pushkey.p12输入导入密码:MAC验证OK输入 PEM 密码:验证 - 输入 PEM 密码:# 删除全局访问的密钥的密码.这只解决了我的 stream_socket_client() &证书容量警告.$ openssl rsa -in PushKey1.pem -out PushKey1_Rmv.pem输入 PushChatKey1.pem 的密码:写入 RSA 密钥# 将两个 .pem 文件合并为一个文件:$ cat PushCert.pem PushKey1_Rmv.pem >应用程序开发文件

然后转到 simplepush.php 位置并触发命令 ->php simplepush.php

通过这种方式,您可以测试您的推送套件通知设置架构.

https://zeropush.com/guide/guide-to-pushkit-and-voip

https://www.raywenderlich.com/123862/push-notifications-tutorial

下载

更新了 Swift 4 代码

导入 UIKit导入 PushKit@UIApplicationMain类 AppDelegate:UIResponder、UIApplicationDelegate、PKPushRegistryDelegate {变量窗口:UIWindow?var isUserHasLoggedInWithApp: Bool = truevar checkForIncomingCall: Bool = truevar userIsHolding: Bool = truefunc application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) ->布尔{如果#available(iOS 8.0, *){让 viewAccept = UIMutableUserNotificationAction()viewAccept.identifier = "VIEW_ACCEPT";viewAccept.title = "接受";viewAccept.activationMode = .ForegroundviewAccept.破坏性 = 假viewAccept.authenticationRequired = false让 viewDecline = UIMutableUserNotificationAction()viewDecline.identifier = "VIEW_DECLINE";viewDecline.title = 拒绝"viewDecline.activationMode = .BackgroundviewDecline.破坏性 = 真viewDecline.authenticationRequired = false让 INCOMINGCALL_CATEGORY = UIMutableUserNotificationCategory()INCOMINGCALL_CATEGORY.identifier = "INCOMINGCALL_CATEGORY";INCOMINGCALL_CATEGORY.setActions([viewAccept,viewDecline], forContext: .Default)if application.respondsToSelector(isRegisteredForRemoteNotifications"){让类别 = NSSet(数组:[INCOMINGCALL_CATEGORY])让类型:UIUserNotificationType = ([.Alert, .Sound, .Badge])让设置:UIUserNotificationSettings = UIUserNotificationSettings(forTypes:类型,类别:类别为?设置)application.registerUserNotificationSettings(settings)application.registerForRemoteNotifications()}}别的{让类型: UIRemoteNotificationType = [.Alert, .Badge, .Sound]application.registerForRemoteNotificationTypes(类型)}self.PushKitRegistration()返回真}//MARK: - PushKitRegistrationfunc PushKitRegistration(){让 mainQueue = dispatch_get_main_queue()//创建一个推送注册对象如果#available(iOS 8.0, *) {让 voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue)//将注册中心的委托设置为 selfvoipRegistry.delegate = self//设置推送类型为VoIPvoipRegistry.desiredPushTypes = [PKPushTypeVoIP]} 别的 {//回退到早期版本}}@available(iOS 8.0, *)func pushRegistry(注册表:PKPushRegistry!,didUpdatePushCredentials 凭据:PKPushCredentials!,forType 类型:字符串!){//向服务器注册 VoIP 推送令牌(PKPushCredentials 的一个属性)让 hexString : String = UnsafeBufferPointer(start: UnsafePointer(credentials.token.bytes),计数:credentials.token.length).map { String(format: "%02x", $0) }.joinWithSeparator("")打印(十六进制字符串)}@available(iOS 8.0, *)func pushRegistry(注册表:PKPushRegistry!,didReceiveIncomingPushWithPayload 有效负载:PKPushPayload!,forType 类型:字符串!){//处理接收到的推送//下面的过程是特定于在收到 pushkit 负载后安排本地通知var arrTemp = [NSObject : AnyObject]()arrTemp = payload.dictionaryPayloadlet dict : Dictionary <String, AnyObject>= arrTemp[aps"] 作为!字典<字符串,任何对象>if isUserHasLoggedInWithApp//检查这个标志然后才继续{if UIApplication.sharedApplication().applicationState == UIApplicationState.Background ||UIApplication.sharedApplication().applicationState == UIApplicationState.Inactive{if checkForIncomingCall//检查此标志以了解来电或其他信息{var strTitle : String = dict[alertTitle"] as?细绳 ??"让 strBody : String = dict[alertBody"] as?细绳 ??"strTitle = strTitle + "\n";+ strBody让notificationIncomingCall = UILocalNotification()notificationIncomingCall.fireDate = NSDate(timeIntervalSinceNow: 1)NotificationIncomingCall.alertBody = strTitleNotificationIncomingCall.alertAction = 打开"notificationIncomingCall.soundName = "SoundFile.mp3";notificationIncomingCall.category = dict[category"] as?细绳 ??"//根据您收到的有效载荷"NotificationIncomingCall.userInfo = [key1":Value1";,key2":Value2";]UIApplication.sharedApplication().scheduleLocalNotification(notificationIncomingCall)}别的{//别的}}}}//MARK: - 本地通知方法func 应用程序(应用程序:UIApplication,didReceiveLocalNotification 通知:UILocalNotification){//你的交互式本地通知事件将在这个地方被调用}}

I have implemented PushKit. Now I want to get Push notifications. Is there nay way to get Push Notifications online as we have many online APNS services which accepts device tokens and .pem file to send remote notifications?

解决方案

You can create your own php file.

Source https://github.com/hasyapanchasara/PushKit_SilentPushNotification

Use below structure to achieve your task.

Use this simplepush.php file

<?php

// Put your device token here (without spaces):

    
      $deviceToken = '1234567890123456789';
//

    
// Put your private key's passphrase here:
$passphrase = 'ProjectName';

// Put your alert message here:
$message = 'My first push notification!';



$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'PemFileName.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$fp = stream_socket_client(
//  'ssl://gateway.push.apple.com:2195', $err,
    'ssl://gateway.sandbox.push.apple.com:2195', $err,
    $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp)
    exit("Failed to connect: $err $errstr" . PHP_EOL);

echo 'Connected to APNS' . PHP_EOL;

// Create the payload body

$body['aps'] = array(
                     'content-available'=> 1,
                     'alert' => $message,
                     'sound' => 'default',
                     'badge' => 0,
                     );

    

// Encode the payload as JSON
    
$payload = json_encode($body);

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));

if (!$result)
    echo 'Message not delivered' . PHP_EOL;
else
    echo 'Message successfully delivered' . PHP_EOL;

// Close the connection to the server
fclose($fp);

Use below commands to create pem file and use it in above code

$ openssl x509 -in aps_development.cer -inform der -out PushCert.pem

# Convert .p12 to .pem. Enter your pass pharse which is the same pwd that you have given while creating the .p12 certificate. PEM pass phrase also same as .p12 cert.  
$ openssl pkcs12 -nocerts -out PushKey1.pem -in pushkey.p12

Enter Import Password:

MAC verified OK

Enter PEM pass phrase:

Verifying - Enter PEM pass phrase:

# To remove passpharse for the key to access globally. This only solved my stream_socket_client() & certificate capath warnings.
$ openssl rsa -in PushKey1.pem -out PushKey1_Rmv.pem

Enter pass phrase for PushChatKey1.pem:

writing RSA key

# To join the two .pem file into one file:
$ cat PushCert.pem PushKey1_Rmv.pem > ApnsDev.pem

After that go to simplepush.php location and fire command -> php simplepush.php

This way you can test your push kit notification setup architecture.

https://zeropush.com/guide/guide-to-pushkit-and-voip

https://www.raywenderlich.com/123862/push-notifications-tutorial

Download

Updated with Swift 4 code

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

}


}

这篇关于如何发送推送通知以在线测试 iOS PushKit 集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆