苹果远程推送实现笔记(iOS)

1.准备工作(developer.apple.com里面完成)

前提有 开发证书ios-dev.cer(iOS Development)  发布用到证书ios-dist.cer(iOS Distribution)

在Identifiers页面点+,添加bundle ID ,例如“com.xxx.yyy”,在配置页面下拉到Push Notifications,勾上,然后右边看到edit链接,点edit会弹窗,提示添加证书(用keychain生成一份push. certSigningRequest),相应导入certSigningRequest文件,这样就可以得到两个证书aps_development.cer(开发用到)和aps.cer(发布用到)

在Profiles页面点+,生成两份配置 push-dev(开发)和push-appstore(发布)其中的identify就选上面那个“com.xxx.yyy”对应的项

在Keys页面点+,随便填个名字,勾选“Apple Push Notifications service (APNs)”,点continue,然后下载保存好,文件名暂定叫push.p8 里面也有一个key ID 假设是“SP12345678”

2. Xcode代码

在AppDelegate.m中加入

#import <UserNotifications/UserNotifications.h>

在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法里面注册通知

[UIApplication sharedApplication].applicationIconBadgeNumber=0;
  /*
   identifier:行为标识符,用于调用代理方法时识别是哪种行为。
   title:行为名称。
   uiusernotificationactivationmode:即行为是否打开app。
   authenticationrequired:是否需要解锁。
   destructive:这个决定按钮显示颜色,yes的话按钮会是红色。
   behavior:点击按钮文字输入,是否弹出键盘
   */
  
  UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"foreground action" options:UNNotificationActionOptionForeground];
  UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action2" title:@"authentication required" options:UNNotificationActionOptionAuthenticationRequired];
  
  UNNotificationCategory *category1 = [UNNotificationCategory categoryWithIdentifier:@"category1" actions:@[action2,action1] intentIdentifiers:@[@"action1",@"action2"] options:UNNotificationCategoryOptionCustomDismissAction];
    
  [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category1, nil]];
  [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
    NSLog(@"completionhandler");
  }];
  
    
  [[UIApplication sharedApplication] registerForRemoteNotifications];
  
  [UNUserNotificationCenter currentNotificationCenter].delegate = self;

再添加两个相应函数:

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error {
    NSLog(@"Registfail%@",error);
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSLog(@"%@",deviceToken);//这里的Token就是我们设备要告诉服务端的Token码,
		unsigned char buffer[1024]={0};
		NSMutableString *mstr = [NSMutableString string];
  for (int i=0; i<deviceToken.length; i++) {
    unsigned char chr = buffer[i];
    [mstr appendFormat:@"%02x",chr];
  }
  NSLog(@"mstr=%@",mstr);  //这个字符串才是需要保存到服务器上面的
	//TODO:发送deviceToken到公司(个人)PHP服务器
}

3. PHP服务器实现:

https://api.sandbox.push.apple.com/3/device/{device-token}  ||dev 开发

https://api.push.apple.com/3/device/{device-token}   || pub 发布

添加 header:

content-type: application/json
apns-topic: com.wancaiinfo.yunzhan365app
apns-priority: 10
apns-push-type: alert
authorization: bearer $jwt

   //badge = 6;   //显示在icon里面的数值

body:

{“aps":{"alert":{"title":"title test","body":"content test"},"badge":6,"sound":"default"}}

其中$jwt = $header.$claims.$signCode

$header=Base64('{ "alg": "ES256", "kid": "SP12345678(上面提到的key ID)” }') 结果要替换+为-,/为_;   暂时定义这个函数名JWTBASE64。

$claims = JWTBASE64('{ "iss": “(teamId 开发组ID,自己developer.apple.com上找)”, "iat": (时间戳)}’);

$signCode= JWTBASE64(sign($header.$claims));  签名后的数据还是要JWTBASE64一把。

sign签名函数可以使用JWT库做到,目前使用加密方法是ES256

4.手动测试(将下面的代码改好,保存为push_test,运行 “chomd +x push_test”加运行权限)

#!/bin/bash

# Get curl with HTTP/2 and openssl with ECDSA: 'brew install curl-openssl'
curl=/usr/bin/curl
openssl=/opt/local/bin/openssl

# --------------------------------------------------------------------------
deviceToken={这里填写在-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken拿到的deviceToken字符串}

authKey="./push.p8"   #(p8文件)
authKeyId=SP12345678 #(key ID)
teamId=Sxxxxxxxxx  # (开发组ID)
bundleId=com.xxx.yyyy  #(Bundle ID)
#endpoint=https://api.development.push.apple.com
endpoint=https://api.sandbox.push.apple.com

read -r -d '' payload <<-'EOF'
{
   "aps": {
      "alert": {
         "title": " test for title",
         "body": "testing ...."
      }
   }
}
EOF

# --------------------------------------------------------------------------

base64() {
   $openssl base64 -e -A | tr -- '+/' '-_' | tr -d =
}

sign() {
   printf "$1"| $openssl dgst -binary -sha256 -sign "$authKey" | base64
}

time=$(date +%s)
header=$(printf '{ "alg": "ES256", "kid": "%s" }' "$authKeyId" | base64)
claims=$(printf '{ "iss": "%s", "iat": %d }' "$teamId" "$time" | base64)
jwt="$header.$claims.$(sign $header.$claims)"

$curl --verbose \
   --header "content-type: application/json" \
   --header "authorization: bearer $jwt" \
   --header "apns-topic: $bundleId" \
   --header "apns-push-type: alert" \
   --data "$payload" \
   $endpoint/3/device/$deviceToken

//----------------后续-----------------

在真机测试是遇到

You've implemented -[<UIApplicationDelegate> application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist.

这个应该是要在项目工程里面"Signing &Capabilities"点+右边的“Capability”,选择“Background Modes”,然后勾上"Remote notifications".

  • 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、付费专栏及课程。

余额充值