弄了快一个星期了 ,我们终于实现远程推送啦,现在把代码附上,客户端只有代码,没弄证书等 的那些步骤,可以在网上搜搜,希望对看到的兄弟有所帮助!!!
客户端:(再得到token值后,需要把token值传给服务器那头来保存,然后有服务器根据token值 来给设备发送信息)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplicationsharedApplication]setApplicationIconBadgeNumber:0];
self.window = [[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]] autorelease];
// Override point for customization after application launch.
//状态条风格设置
[application setStatusBarStyle:UIStatusBarStyleBlackOpaque];
//hide 状态条
[application setStatusBarHidden:NOanimated:YES];
//idle有效
[UIApplicationsharedApplication].idleTimerDisabled =NO;
//初始化界面
[selfsetupInterface];
if ([DMUserConfigisFirst]) {
[selfshowGuideView];
}
// self.window.backgroundColor = [UIColor whiteColor];
[self.windowmakeKeyAndVisible];
//chenyong 推送通知test--------------------------begin
[[UIApplicationsharedApplication]registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert |UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];
//判断程序是不是由推送服务完成的
//chenyong 这个不让弹出警告了
// if (launchOptions) {
// NSDictionary* pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
// if (pushNotificationKey) {
// UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"推送通知"
// message:@"这是通过推送窗口启动的程序,你可以在这里处理推送内容"
// delegate:nil
// cancelButtonTitle:@"知道了"
// otherButtonTitles:nil, nil];
// [alert show];
// [alert release];
// }
// }
//chenyong--------------------------------------end
return YES;
}
//chenyong 推送通知CODE-------------------------------------------------begin
- (void)sendProviderDeviceToken: (NSString *)deviceTokenString
{
// Establish the request
NSLog(@"sendProviderDeviceToken = %@", deviceTokenString);
NSString *UDIDString = [[UIDevicecurrentDevice]uniqueIdentifier];
NSString *body = [NSStringstringWithFormat:@"action=savetoken&clientid=%@&token=%@", UDIDString, deviceTokenString];
// NSString *baseurl = [NSString stringWithFormat:@"%@?",@"http://www.ganchi.net/x_search.php"]; //服务器地址
NSString *baseurl = [NSStringstringWithFormat:@"%@?",@"http://www.ganchi.net/x_token.php"];//cyy改发此地址
NSLog(@"send provider device token = %@", baseurl);
NSURL *url = [NSURLURLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequestrequestWithURL:url];
[urlRequest setHTTPMethod: @"POST"];
[urlRequest setHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];
// NSLog(@"urlRequest.url is %@",urlRequest.URL);//chenyong 为什么打印出来的仍是不带参数哩
NSURLConnection *tConnection = [[NSURLConnectionalloc]initWithRequest: urlRequestdelegate:self];
// self.deviceTokenConnetion = [tConnection retain];
[tConnection release];
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [NSStringstringWithFormat:@"%@",deviceToken];
token = [[token substringWithRange:NSMakeRange(0,72)]substringWithRange:NSMakeRange(1,71)];
token = [token stringByReplacingOccurrencesOfString:@" "withString:@""];
NSLog(@"apns->生成的token值是:%@",token);
[selfsendProviderDeviceToken:token];
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@"apns->注册推送功能时发生错误,错误信息:%@",error);
}
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(@"\napns -> didReceiveRemoteNotification,Receive Data:\n%@", userInfo);
//把icon上的标记数字设置为0,
application.applicationIconBadgeNumber =0;
//chenyong 不让弹出警告了
// if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"]!=NULL) {
// UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"**推送消息**"
// message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]
// delegate:self
// cancelButtonTitle:@"关闭"
// otherButtonTitles:@"处理推送内容",nil];
alert.tag = alert_tag_push; //chenyong 这个地方不知道有什么用,原来是有的,但注释掉后好像也行
// [alert show];
// }
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
服务端php实现:(有一点需要注意:听群里的兄弟说如果想推送系统音频,就直接 $sound = 'default'; 就行,但如果想推送别的音频,貌似需要在客户端加上该音频文件,然后再处理下)
<?php
define('IN_ECS', true);
Header("Content-type:text/html;charset=uft-8");
require('../includes/init.php');
//如果有新活动,推送每个token
// activity表所有act_id,组成一维数组和push表中act_id进行比较找差集,得到活动数量
$actarr = array();
$sql = "select act_id from activity ";
$res = $GLOBALS['db'] -> getAll($sql);
foreach ($res as $key => $value) {
$actupdateid .= $value['act_id'].',';
$actarr[$key] = $value['act_id'] ;
}
// echo $actupdateid;
$sql = "select DISTINCT(token), act_id from push ";
$res1 = $GLOBALS['db'] -> getAll($sql);
foreach ($res1 as $k => $v) {
$aaa = explode(',', $v['act_id']);
$result = array_diff($actarr ,$aaa);
//更新的活动数
$dif = count($result);
//如果有活动更新
if (!empty($dif)) {
// $sql = "select distinct(token) from push ";
// $res = $GLOBALS['db'] -> GetAll($sql);
// //往所有token发送信息
// foreach ($res as $key => $value) {
// Put your device token here (without spaces):
$deviceToken = $v['token'];
// Put your private key's passphrase here:
$passphrase = '新消息';
// Put your alert message here:
//$message = '啊封口蜡昆仑山发可了';
// Get the parameters from http get or from command line
$message = $_GET['message'] or $message = $argv[1] or $message ='有新活动上线了。';
//$badge = (int)$_GET['badge'] or $badge = (int)$argv[2] or $badge = 11;
$badge = 1;
$sound = 'default';
//$sound = $_GET['sound'] or $sound = $argv[3];
// Construct the notification payload
$body = array();
$body['aps'] =array('alert' => $message);
if ($badge)
if ($sound)
$body['aps']['badge'] = $badge;
$body['aps']['sound'] = $sound;
/* End of Configurable Items */
$ctx = stream_context_create();
stream_context_set_option($ctx,'ssl','local_cert', 'iostest_push_dev.pems');
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'
//);
// 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;
//print "Sending message :" . $payload . "\n";
//fwrite($fp, $msg);
//fclose($fp);
// 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;
//如果消息推送成功,则更新此token的act_id值
$sql ="update push set act_id = '$actupdateid' where token = '$v[token]'";
$res = $GLOBALS['db'] -> query($sql);
// Close the connection to the server
fclose($fp);
//}
//如果没有活动更新
}else{
$sql ="select act_id from activity ";
$res = $GLOBALS['db'] -> getAll($sql);
foreach ($resas $key => $value) {
$actupdateid.= $value['act_id'].',';
}
//print_r($actupdateid);
//echo $v['token'];
$sql ="update push set act_id = '$actupdateid' where token = '$v[token]'";
$res = $GLOBALS['db'] -> query($sql);
}
}