如何获取设备令牌

ste*_*k21 5 php xcode push-notification apple-push-notifications devicetoken

我有一个适用于iOS的应用程序,我想集成那里的推送通知。我在 youtube 上看过一个教程,一切正常,但最近我正在使用开发证书(用于测试 - 不是用于 AppStore),并且我的服务器上有 PHP 脚本。在这个文件中存储有我的 iPhone 的 deviceToken,它是用 php 变量 $deviceToken 编写的。但是现在,当我想在 AppStore 中使用它时,如何从下载我的应用程序的每个人那里获取设备令牌并将其放入 PHP 脚本中?

这是我的 PHP 文件:

 if($_POST['message']){

        $deviceToken = '(my device token)';

        $message = stripslashes($_POST['message']);

        $payload = '{
                        "aps" : 

                            { "alert" : "'.$message.'",
                              "badge" : 1,
                              "sound" : "bingbong.aiff"
                            } 
                    }';

        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', 'cert.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', 'password');
        $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
        if(!$fp){
            print "Failed to connect $err $errstrn";
            return;
        } else {
            print "DONE!";
        }

        $devArray = array();
        $devArray[] = $deviceToken;

        foreach($devArray as $deviceToken){
            $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack        ("n",strlen($payload)) . $payload;
            fwrite($fp, $msg);
        }
        fclose($fp);
    }

<form action="send-notification.php" method="post">
    <input type="text" name="message" maxlength="100">
    <input type="submit" value="SEND">
</form>
</body>
Run Code Online (Sandbox Code Playgroud)

这就是我在 xCode (AppDelegate.m) 中所拥有的

   - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];

    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *deviceTokenString = [NSString stringWithFormat:@"%@", deviceToken];
    NSLog(deviceTokenString);
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 2

好吧,我不懂PHP,所以我不能给你具体的代码,但我可以解释一下一般原理。

当您的应用程序启动时,您应该通过调用该方法来注册 Apple 推送通知registerForRemoteNotificationTypes:

当注册成功并且您获得设备令牌时,您应该在实现中将其发送到您的服务器application:didRegisterForRemoteNotificationsWithDeviceToken:

您的服务器应该将其存储在某个数据库中。

发送通知的 PHP 脚本应该从该数据库获取设备令牌。