简体   繁体   中英

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. 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


// 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:

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." 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

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. Please help! Any suggestions or insight you have will be appreciated!

The link does tell you what to do with the PHP script. You aren't suppose to call that through 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. You can run this straight from your Mac.

...

You should copy the device token from the app into the $deviceToken variable. Be sure to leave out the spaces and brackets; it should just be 64 hexadecimal characters. Put your private key's passphrase into $passphrase, and the text you wish to send in $message. Copy your ck.pem file into the SimplePush folder. Remember, the ck.pem file contains both your certificate and the private key.

Then open a Terminal and type: .....

The PHP is a simple example of what your server would do. You need to build the server as well that will invoke a call to apple's APNS when a certain event occurs. The mobile app itself doesn't invoke a push notification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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