ios 推送

今天跟大家分享一下推送。

今天终于把推送搞定了,其实很简单,但是遇到两个问题,1.deviceToken的引用格式(应该去掉尖括号并且有空格)。2.配置文件选择证书问题,选的不是新建的推送证书。

首先,如果英语还凑活的童鞋我建议看一下官网,apns讲的很好,虽然我看官网也很费劲,但是看过官网的东西还是觉得很赞。

下面是官网的两张图简单介绍一下原理:

Figure 3-1  A push notification from a provider to a client application

这个图很直观的说明了推送的原理:服务器想发推送给你的设备,他会先将token和payload发送到apns 然后apns 根据token找到你的device,接着将消息发到你的app上。token就是你的机器标识,payload包含了消息的一些内容。




device token的生成是这样的,app发送注册推送功能的请求给device,然后device根据请求链接到apns并将请求发给apns,apns收到请求后生成device token然后反馈给device,然后device再反馈给app,之后app将device token发给provider,provider用这个device token 给机器推送消息。

原理就简单介绍到这里,如果童鞋们想了解更多可以到官方文档看一下,那里还有好些流程图。了解原理之后我们最重要的事儿,就是推送证书了。


推送证书主要包括这四个文件:

第一个:CSR文件,在mac的钥匙串里面生成。

第二个:apns_development证书,需要在开发者中心网站生成。

第三个:开发证书,这个一般是你的开发者账号命名的开发证书。

第四个:配置文件,包含你的appId和第三个文件等。

这个文件如何生成的具体过程我就不说了,网上有很清楚的图文教程。这里大家要注意:

文件产生的顺序:csr--开发证书---app id --- ssl --- provisioning profile。

生成provisioning profile文件时需要选择证书,这里选择的证书并不是apns证书,而是开发证书一般就是你账号中以账号命名的证书。

证书都安装好之后基本就ok了。

客户端代码:

1.注册推送功能

<span style="font-size:10px;"><span style="font-size:12px;">- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    //let the divce know we want to receive push notifications
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    return YES;
}</span></span>

2.注册成功返回token,并发给服务器

<span style="font-size:10px;"><span style="font-size:12px;">- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);
    
    NSString *pushToken = [[[deviceToken description]
                             stringByReplacingOccurrencesOfString:@"<" withString:@""]
                            stringByReplacingOccurrencesOfString:@">" withString:@""];
    
    [self sendDeviceTokenToPushServer:pushToken];
    
}</span></span>


3.接受到推送消息后处理

<span style="font-size:10px;"><span style="font-size:12px;">- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"Receive remote notification : %@",userInfo);
    
    UIAlertView *alert =
    [[UIAlertView alloc] initWithTitle:@"温馨提示"
                               message:@"推送成功!"
                              delegate:nil
                     cancelButtonTitle:@"确定"
                     otherButtonTitles:nil];
    [alert show];
}</span></span>

4.发送token给服务器代码,这个方法有很多中写法,这里使用了AFNetWorking框架进行网络请求

<span style="font-size:10px;"><span style="font-size:12px;">- (void)sendDeviceTokenToPushServer: (NSString *)deviceTokenString
{
    // Establish the request
    NSLog(@"sendProviderDeviceToken = %@", deviceTokenString);
    
    NSString *UUIDString = [[UIDevice currentDevice].identifierForVendor UUIDString];
    NSString *body = [NSString stringWithFormat:@"action=savetoken&clientid=%@&token=%@", UUIDString, deviceTokenString];
    
    NSString *baseurl = [NSString stringWithFormat:@"%@?",@"http://106.2.178.58/push_chat_service.php"];
    NSURL *url = [NSURL URLWithString:baseurl];
    
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:urlRequest];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"send deviceToken successed!");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"send deviceToken failed!");
    }];
    [operation start];
}</span></span>

服务器端:

可以用pushMeBaby for mac这个软件当做服务器来测试一下推送功能。

当然,一般情况下我们的服务器在windows系统下搭建,这样我们需要把我们的证书转换成.pem格式,这样windows系统才能够识别。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现iOS推送,需要遵循以下步骤: 1. 创建APNS证书 首先,你需要在苹果开发者中心创建一个APNS证书。这个证书将用于安全地将消息发送到iOS设备。 2. 获取设备Token 每个iOS设备都有一个唯一的设备Token,用于标识该设备。你需要在你的应用中获取该设备Token,并将其发送到你的服务器。 3. 编写PHP代码 使用PHP编写代码,以便将消息发送到APNS服务器。你需要使用APNS证书和设备Token来建立连接,并将消息发送到APNS服务器。 以下是一个简单的PHP代码示例: ``` <?php // Put your device token here (without spaces): $deviceToken = 'YOUR_DEVICE_TOKEN_HERE'; // Put your private key's passphrase here: $passphrase = 'YOUR_PASSPHRASE_HERE'; // Put your alert message here: $message = 'Hello, world!'; //////////////////////////////////////////////////////////////////////////////// $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'YOUR_APNS_CERTIFICATE.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' ); // 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 the notification 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); ?> ``` 在上面的代码中,你需要将以下变量替换为你自己的值: - YOUR_DEVICE_TOKEN_HERE:你的设备Token。 - YOUR_PASSPHRASE_HERE:你的APNS证书密码。 - YOUR_APNS_CERTIFICATE.pem:你的APNS证书文件名和路径。 - $message:你要发送的消息。 4. 测试推送 运行PHP代码并测试推送。如果一切正常,你应该会收到一个推送通知。 注意:在生产环境中,你需要将APNS服务器地址更改为“gateway.push.apple.com”。在示例代码中,我们使用的是开发环境的APNS服务器地址“gateway.sandbox.push.apple.com”。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值