2017-06-16 27 views
0

我resultString是「PHNhbWxwOlJlc3BvbnNlIH ... c3BvbnNlPgoK」,當我解碼它顯示我作爲decodedData爲零。initWithBase64EncodedString回零

的NSData * decodedData = [[NSData的頁頭] initWithBase64EncodedString:resultString選項:0];

我也試過這個字符串https://www.base64decode.org/, 它成功地顯示結果。

這裏解碼有什麼問題?

+1

你甚至試圖所以搜索一下嗎? :|希望此鏈接將幫助您 https://stackoverflow.com/questions/19088231/base64-decoding-in-ios-7 –

+0

是我第一次嘗試搜索,然後我張貼。 –

回答

0

試試這個!簡單的解決方案:)必須需要Foundation.framework。默認情況下,當輸入未被識別爲有效的Base-64時,initWithBase64EncodedString方法返回nil。請檢查您的字符串是否是有效的Base-64類型!

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:@"eyJuYW1lIjoidmlnbmVzaCJ9" options:0]; 
    NSError *dataError; 
    NSDictionary* responseObject = [NSJSONSerialization JSONObjectWithData:decodedData 
               options:kNilOptions 
                error:&dataError]; 
    if(dataError == nil) { 
     NSLog(@"Result %@",responseObject); 
    } 
+0

在這裏,decodedData是零,所以它崩潰了。 –

+0

你有沒有在你的項目中添加基礎框架?結果{name} = vignesh; } –

+0

@KrishSolanki,請提供樣本編碼字符串。 –

0

幾乎可以肯定你的字符串是無效的Base64,但它是「足夠接近」,base64decode.org接受它。最可能的原因是你已經下降了尾隨=。 base64decode.org是容忍的,只是靜靜地拋棄它無法解碼的東西(在這種情況下的最後一個字節)。 NSData不容忍,因爲它不是有效的Base64。

base64decode.org也可以容忍字符串中的隨機非base64字符,並將它們丟棄。 NSData不是(再次,正弦它是無效的)。

1

也許你有一些無效字符在你的字符串,如填充新的生產線。嘗試通過NSDataBase64DecodingIgnoreUnknownCharacters選項而不是0

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:resultString options:NSDataBase64DecodingIgnoreUnknownCharacters];