从 PHP 推送通知向 iOS 发送变量?
Posted
技术标签:
【中文标题】从 PHP 推送通知向 iOS 发送变量?【英文标题】:Send variables to iOS from PHP push notification? 【发布时间】:2011-07-30 16:48:58 【问题描述】:我正在使用 php 脚本向我的设备发送推送通知。这是我用的
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
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);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'id' => '10'
);
// 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;
echo "to $deviceToken.";
// Close the connection to the server
fclose($fp);
我成功了。我点击查看按钮,并尝试像这样读取“id”变量:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// Check for push notification info
NSDictionary *pushInfo = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (pushInfo)
// TODO: Pull the poke's info from our server and update the UI to display it
NSLog(@"Here's the id: %@", [pushInfo valueForKey:@"id"]);
return YES;
但是,在多任务处理时,我没有收到 NSLog。关闭应用程序时我还没有尝试过,因为关闭后我无法运行控制台。
我什至试过这个:
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
// Handle the notificaton when the app is running
NSLog(@"Recieved Notification %@",notif);
如果我在运行时发送通知,我什至不会收到 NSLog。怎么回事?
提前致谢!
【问题讨论】:
【参考方案1】:NSDictionary *pushInfo = [launchOptions valueForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"] objectForKey:@"aps"]];
【讨论】:
使用字符串文字可能不是正确的解决方案;常量符号UIApplicationLaunchOptionsRemoteNotificationKey
在Apple 的UIApplication.h 头文件中定义;我会谨慎避免使用预定义的符号,因为它们确实是定义明确的公共 API 的一部分。以上是关于从 PHP 推送通知向 iOS 发送变量?的主要内容,如果未能解决你的问题,请参考以下文章