简体   繁体   English

如何运行PHP脚本发送推送通知

[英]how to run php script for sending push notification

I need help implementing push notifications in swift. 我需要迅速实施推送通知的帮助。 I followed the ray wenderlich tutorial http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1 but it does not mention how you actually call or run the php push notification script in Xcode. 我遵循了ray wenderlich教程http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1 ,但未提及您实际上如何调用或运行php Xcode中的推送通知脚本。 This is how I am attempting to call the script right now: 这就是我现在尝试调用脚本的方式:

    let request = NSMutableURLRequest(URL: NSURL(string: "http://website.com/pushNotification")!)
    request.HTTPMethod = "POST"

    let dataDictionary:[String:String] = ["NotificationData":"\(deviceTokenString)<*&*>password<*&*>my first push notification"]

    let data:NSData = try! NSJSONSerialization.dataWithJSONObject(dataDictionary, options: [])
    request.HTTPBody = data

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    // Create a NSURLSession task with completion handler
    let task:NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        // Convert the data into a dictionary
        let response:[String:String] = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! [String:String]


        // Check if there was an error
        if let result = response["result"] {
            if result == "success"{

                NSLog("Message deleviered successfully")


            }
            else if result == "error"{
                NSLog("Message could not be deleviered")
            }

        }

    })

    // Run the task
    task.resume()

Heres the php script it hits: 这是它命中的PHP脚本:

<?php


// Get the data from the request
$json = file_get_contents('php://input');
$data = json_decode($json, true);
$pushData = $data['NotificationData'];

// Format data
$keywords = explode("<*&*>", $pushData);

// Assign data into variables
$deviceToken = $keywords[0];
$passphrase = $keywords[1];
$message = $keywords[2];

////////////////////////////////////////////////////////////////////////////////

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'signingcertificate.p12');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$fp = stream_socket_client(
    '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);
}


// Create the payload body
$body['aps'] = array(
    'alert' => $message,
    'sound' => 'default'
    );

// 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 '{"result" : "error"}';
}
else {
    echo '{"result" : "success"}';
}
// Close the connection to the server
fclose($fp);

?>

But then Xcode gives me this error: 但是然后Xcode给我这个错误:

fatal error: 'try!' 致命错误:“尝试!” expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." 该表达式意外引发错误:Error Domain = NSCocoaErrorDomain代码= 3840“ JSON文本不是以数组或对象开头,并且选项未设置片段。” UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}: file /Library/Caches/com.apple.xbs/Sources/swiftlang_PONDEROSA/swiftlang_PONDEROSA-700.1.101.6/src/swift/stdlib/public/core/ErrorType.swift, line 50 UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,并且没有设置片段的选项。}:文件/Library/Caches/com.apple.xbs/Sources/swiftlang_PONDEROSA/swiftlang_PONDEROSA-700.1.101.6/src/swift/ stdlib / public / core / ErrorType.swift,第50行

Im almost positive the error has something to do with the way I call for the php script but I don't know how this type of php script should be called. 我几乎肯定该错误与我调用php脚本的方式有关,但我不知道应该如何调用这种类型的php脚本。 Please help! 请帮忙! Any suggestions or insight you have will be appreciated! 您的任何建议或见解将不胜感激!

The link does tell you what to do with the PHP script. 该链接确实告诉您如何使用PHP脚本。 You aren't suppose to call that through Xcode. 您不应通过Xcode调用它。

As the tutorial states: 如本教程所述:

As I've mentioned a few times before, you need to set up a server that sends the push notifications to your app. 正如我之前提到过的,您需要设置一台将推送通知发送到您的应用程序的服务器。 For this first test, you're not going to set up a server just yet. 对于此第一个测试,您现在尚未设置服务器。 Instead, I'll give you a very simple PHP script that sets up a connection to APNS and sends a push notification to a device token that you specify. 相反,我将给您一个非常简单的PHP脚本,该脚本建立与APNS的连接,并向您指定的设备令牌发送推送通知。 You can run this straight from your Mac. 您可以直接在Mac上运行。

... ...

You should copy the device token from the app into the $deviceToken variable. 您应该将设备令牌从应用程序复制到$ deviceToken变量中。 Be sure to leave out the spaces and brackets; 请确保省略空格和方括号; it should just be 64 hexadecimal characters. 它只能是64个十六进制字符。 Put your private key's passphrase into $passphrase, and the text you wish to send in $message. 将私钥的密码短语放入$ passphrase,然后将希望发送的文本放入$ message。 Copy your ck.pem file into the SimplePush folder. 将您的ck.pem文件复制到SimplePush文件夹中。 Remember, the ck.pem file contains both your certificate and the private key. 请记住,ck.pem文件包含您的证书和私钥。

Then open a Terminal and type: ..... 然后打开一个终端并键入:.....

The PHP is a simple example of what your server would do. PHP是服务器将执行的简单示例。 You need to build the server as well that will invoke a call to apple's APNS when a certain event occurs. 您还需要构建服务器,该服务器在发生特定事件时将调用对苹果APNS的调用。 The mobile app itself doesn't invoke a push notification. 移动应用程序本身不会调用推送通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM