33

オブジェクトの形で iPhone デバイス トークンを受け取っていNSDataます。通知スクリプト関数をテストしたとき、そのオブジェクトをログからコピーしただけで、通知はうまくいきました。ただし、今自動的に実行しようとすると、デバイス トークンを変数の形式で ASCII エンコードされた文字列として送信しています。

self.deviceToken = [[NSString alloc] initWithData:webDeviceToken encoding:NSASCIIStringEncoding];

私が取得している文字列にはいくつかのファンキーな文字があり、これに似ています"å-0¾fZÿ÷ʺÎUQüRáqEªfÔk«"

サーバー側のスクリプトがそのトークンに通知を送信すると、何も受信しません。

何かをデコードする必要がありますか?

よろしく

4

6 に答える 6

108

わかりました、解決策を見つけました。誰かが同じ問題を抱えている場合は、ASCII エンコーディングを忘れて、次の行で文字列を作成してください。

NSString *deviceToken = [[webDeviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
deviceToken = [deviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
于 2009-10-19T07:58:02.667 に答える
43

誰かが Swift でこれを行う方法を探している場合:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    print("tokenString: \(tokenString)")
}

編集:Swift 3の場合

Swift 3 では、Data値のセマンティクスを持つ型が導入されています。を文字列に変換するdeviceTokenには、次のようにします。

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    var token: String = ""
    for i in 0..<deviceToken.count {
        token += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
    }

    print(token)
}
于 2014-07-27T10:17:14.987 に答える
5

iOS は将来のバージョンで説明の使用法を変更できるため、このソリューションの方が優れていることがわかりました。そのため、データで説明プロパティを使用すると、将来的に信頼できなくなる可能性があります。データ トークン バイトから 16 進トークンを作成することで、これを直接使用できます。

 - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
 const unsigned *tokenBytes = [deviceToken bytes];
 NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                  ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                  ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                  ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
 [[MyModel sharedModel] setApnsToken:hexToken];

}

デバイス トークンを NSUserdefaults に保存し、後でそれを使用してサーバーに送信することもできます。

于 2013-08-30T14:34:11.113 に答える
2

Appleサーバーに通知を送信する前に文字列を再構築する必要があるため、これは良い解決策ではないと思います。文字列などを送信するには、Base64エンコーディングを使用します。

于 2009-10-19T09:22:01.793 に答える
0

デバイス トークンを 16 進数文字列に変換する別の方法

NSUInteger capacity = [deviceToken length] * 2;
NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:capacity];
const unsigned char *dataBuffer = [deviceToken bytes];
NSInteger i;
for (i=0; i<[deviceToken length]; ++i) {
    [stringBuffer appendFormat:@"%02X", (NSUInteger)dataBuffer[i]];
}
NSLog(@"token string buffer is %@",stringBuffer);
于 2013-12-16T09:25:19.770 に答える