推送参考

IOS开发之实现App消息推送

主要流程

  • 1.你的IOS应用需要去注册APNS消息推送功能。
  • 2.当苹果APNS推送服收到来自你应用的注册消息就会返回一串device token给你(很重要)
  • 3.将应用收到的device Token传给你本地的Push服务器。
  • 4.当你需要为应用推送消息的时候,你本地的推送服务器会将消息,以及Device Token打包发送到苹果的APNS服
  • 5.APNS再将消息推送给目的iphone

注册远程推送


//注册时调用
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //register to receive notifications
    [application registerForRemoteNotifications];
}

//收到通知时调用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    // 消息通知跳转
    PKLog(@"userInfo == %@",userInfo);
    }
    
//失败时调用
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    
    PKLog(@"Regist fail%@",error);
}
//注册成功后会得到设备的deviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken{
    
    self.updateTimes += 1;
    if (self.updateTimes > 1) return;
    
    PKLog(@"++++++++++++++++++++++++++%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                  stringByReplacingOccurrencesOfString: @">" withString: @""]
                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    
    
    NSString *dtString = [deviceToken description];
    NSString *dt = [dtString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSString *token = [dt stringByReplacingOccurrencesOfString:@" " withString:@""];

    // 发送更新iOS的token信息通知
    [[NSNotificationCenter defaultCenter] postNotificationName:TransferDeviceTokenNotification object:self userInfo:@{@"token" : token}];
}

截取token

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken{
    
    self.updateTimes += 1;
    if (self.updateTimes > 1) return;
    
    PKLog(@"++++++++++++++++++++++++++%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                  stringByReplacingOccurrencesOfString: @">" withString: @""]
                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    
    
    NSString *dtString = [deviceToken description];
    NSString *dt = [dtString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSString *token = [dt stringByReplacingOccurrencesOfString:@" " withString:@""];

    // 发送更新iOS的token信息通知
    [[NSNotificationCenter defaultCenter] postNotificationName:TransferDeviceTokenNotification object:self userInfo:@{@"token" : token}];
}

token回传后端

//注册消息
[[NSNotificationCenter defaultCenter] postNotificationName:TransferDeviceTokenNotification object:self userInfo:@{@"token" : token}];

//接收消息
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateiOSToken:) name:TransferDeviceTokenNotification object:nil];

//更新iOS的token信息
- (void)updateiOSToken:(NSNotification *)noti
{
    if (self.userInfo.uid == 0 || self.userInfo.sid == nil) return;
    
    NSString *token = noti.userInfo[@"token"];
    
    if (token == nil) {
        return;
    }
    
    NSDictionary *dic = [PKApiService recordIosTokenWithuid:self.userInfo.uid sid:self.userInfo.sid token:token];
    
    int statusCode = [[dic objectForKey:@"statusCode"] intValue];
    
    if (statusCode == 2000000)          // 成功
    {
        // 创建用户信息模型,并赋值
        PKUserInfo *userInfo = [PKUserInfoTool userInfo];
        userInfo.token = token;
        [PKUserInfoTool saveUserInfo:userInfo];
        
        PKLog(@"更新iOS的token信息---发送成功");
        
    } else {                            // 失败
        PKLog(@"更新iOS的token信息--发送失败--%d",statusCode);
     }
}

模拟推送服务器

  • deviceToken为端注册远程成功后回传参数
<?php  
  
// ??????????deviceToken???????????????  
$deviceToken = 'c95f661371b085e2517b4c12cc76293522775e5fd9bb1dea17dd80fe85583b41';  
  
// Put your private key's passphrase here:  
$passphrase = 'abc123';  
  
// Put your alert message here:  
$message = 'My first push test!';  
  
////////////////////////////////////////////////////////////////////////////////  
  
$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.push.apple.com:2195?, $err, $errstr, 60, //STREAM_CLIENT_CONNECT, $ctx);  
//?????????????appstore??????  
$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;  
  
// 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;  
  
// Close the connection to the server  
fclose($fp);  
?>