集成 APNs

接入 APNs 分三步:开启 Xcode 能力、在 AppDelegate 注册远程通知、把拿到的 deviceToken 交给 IMLib 登记。

1. 开启能力​

  1. Xcode → Target → Signing & Capabilities → + Capability → Push Notifications。
  2. 需要后台唤醒时再加 Background Modes → Remote notifications。
  3. 确认 provisioning profile 包含推送 entitlement(`aps-environment` = development / production)。
  4. 在 Apple Developer 后台准备 APNs Auth Key(.p8,推荐)或推送证书,配置到 IM 服务端。

2. 注册远程通知​

// ios-imlib/push/apns
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, _ in }
@interface AppDelegate () <UNUserNotificationCenterDelegate>
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    [[UNUserNotificationCenter currentNotificationCenter]
        requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound)
                      completionHandler:^(BOOL granted, NSError *error) {
        if (!granted) { return; }   // 用户拒绝:引导去系统设置开启
        dispatch_async(dispatch_get_main_queue(), ^{
            [application registerForRemoteNotifications];
        });
    }];
    return YES;
}

- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSMutableString *token = [NSMutableString string];
    const unsigned char *bytes = deviceToken.bytes;
    for (NSUInteger i = 0; i < deviceToken.length; i++) {
        [token appendFormat:@"%02x", bytes[i]];
    }
    [PushTokenStore.shared uploadToken:token];   // 调 IMLib registerPushToken
}

- (void)application:(UIApplication *)application
    didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"APNs register failed: %@", error);
}
@end

3. 环境与证书​

环境用途APNs 主机
Development(sandbox)Debug 构建 / 开发证书api.sandbox.push.apple.com
ProductionRelease / TestFlight / App Storeapi.push.apple.com
Auth Key(.p8)推荐:一个 Key 覆盖开发与生产Key ID + Team ID 配置在服务端
证书(.p12)旧方式:开发 / 生产各一张证书过期会导致推送静默失败
sandbox 与 production 不通用

Debug 包拿到的 deviceToken 只能走 sandbox;服务端配置错环境是“客户端已登记但收不到推送”的最常见原因。

自检清单​

  • Capability 里能看到 Push Notifications 与 aps-environment。
  • 首次启动弹出通知权限;拒绝后可在「设置 → 通知 → 你的 App」重新开启。
  • `didRegisterForRemoteNotificationsWithDeviceToken` 有回调且 token 非空。
  • 服务端可查询到该用户与平台的活跃 token(`getPushTokens`)。
  • 真机锁屏后由对端发消息,能收到通知;点击进入正确会话。