ios 将 UTF-8 编码的 NSData 转换为 NSString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2467844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert UTF-8 encoded NSData to NSString
提问by Ashwini Shahapurkar
I have UTF-8 encoded NSData
from windows server and I want to convert it to NSString
for iPhone. Since data contains characters (like a degree symbol) which have different values on both platforms, how do I convert data to string?
我有NSData
从 Windows 服务器编码的 UTF-8 ,我想将其转换NSString
为 iPhone。由于数据包含在两个平台上具有不同值的字符(如度数符号),我如何将数据转换为字符串?
回答by kennytm
If the data is not null-terminated, you should use -initWithData:encoding:
如果数据不是以空值结尾的,你应该使用 -initWithData:encoding:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
If the data is null-terminated, you should instead use -stringWithUTF8String:
to avoid the extra \0
at the end.
如果数据以空值结尾,则应改为使用-stringWithUTF8String:
避免\0
末尾的额外数据。
NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];
(Note that if the input is not properly UTF-8-encoded, you will get nil
.)
(请注意,如果输入的 UTF-8 编码不正确,您将获得nil
.)
Swift variant:
Swift 变体:
let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.
If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.
如果数据以空字符结尾,您可以通过删除该空字符的安全方法,或类似于上述 Objective-C 版本的不安全方法。
// safe way, provided data is +(id)stringWithUTF8String:(const char *)bytes.
-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is @interface NSData (EasyUTF8)
// Safely decode the bytes into a UTF8 string
- (NSString *)asUTF8String;
@end
-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))
回答by Gouldsc
You could call this method
你可以调用这个方法
@implementation NSData (EasyUTF8)
- (NSString *)asUTF8String {
return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}
@end
回答by Claudiu
I humbly submit a category to make this less annoying:
我谦虚地提交一个类别,使这不那么烦人:
NSData *data = ...
[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
and
和
NSData *data = ...
[data asUTF8String];
(Note that if you're not using ARC you'll need an autorelease
there.)
(请注意,如果您不使用 ARC,则需要在autorelease
那里使用。)
Now instead of the appallingly verbose:
现在,而不是令人震惊的冗长:
extension Data {
var string: String? {
return String(data: self, encoding: .utf8)
}
}
You can do:
你可以做:
extension StringProtocol {
var data: Data {
return Data(utf8)
}
}
回答by Leo Dabus
The Swift version from String to Data and back to String:
从 String 到 Data 再到 String 的 Swift 版本:
Xcode 10.1 ? Swift 4.2.1
Xcode 10.1?斯威夫特 4.2.1
extension String {
var base64Decoded: Data? {
return Data(base64Encoded: self)
}
}
let string = "Hello World" // "Hello World"
let stringData = string.data // 11 bytes
let base64EncodedString = stringData.base64EncodedString() // "SGVsbG8gV29ybGQ="
let stringFromData = stringData.string // "Hello World"
let base64String = "SGVsbG8gV29ybGQ="
if let data = base64String.base64Decoded {
print(data) // 11 bytes
print(data.base64EncodedString()) // "SGVsbG8gV29ybGQ="
print(data.string ?? "nil") // "Hello World"
}
Playground
操场
let stringWithAccent = "Olá Mundo" // "Olá Mundo"
print(stringWithAccent.count) // "9"
let stringWithAccentData = stringWithAccent.data // "10 bytes" note: an extra byte for the acute accent
let stringWithAccentFromData = stringWithAccentData.string // "Olá Mundo\n"
NSData *signature;
NSString *signatureString = [signature base64EncodedStringWithOptions:0];
let signatureString = signature.base64EncodedStringWithOptions(nil)
回答by mikeho
Sometimes, the methods in the other answers don't work. In my case, I'm generating a signature with my RSA private key and the result is NSData. I found that this seems to work:
有时,其他答案中的方法不起作用。就我而言,我使用 RSA 私钥生成签名,结果是 NSData。我发现这似乎有效:
Objective-C
目标-C
[NSString stringWithUTF8String:(char *)data.bytes];
Swift
迅速
[[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];
回答by Gal
Just to summarize, here's a complete answer, that worked for me.
总结一下,这是一个完整的答案,对我有用。
My problem was that when I used
我的问题是当我使用
init?(data: Data, encoding: String.Encoding)
The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with Null
or even worse: garbaged at the end of the string.
我得到的字符串是不可预测的:大约 70% 它确实包含预期值,但它经常导致Null
甚至更糟:在字符串末尾垃圾。
After some digging I switched to
经过一番挖掘,我切换到
import Foundation
let json = """
{
"firstName" : "John",
"lastName" : "Doe"
}
"""
let data = json.data(using: String.Encoding.utf8)!
let optionalString = String(data: data, encoding: String.Encoding.utf8)
print(String(describing: optionalString))
/*
prints:
Optional("{\n\"firstName\" : \"John\",\n\"lastName\" : \"Doe\"\n}")
*/
And got the expected result every time.
并且每次都得到了预期的结果。
回答by Imanou Petit
With Swift 5, you can use String
's init(data:encoding:)
initializer in order to convert a Data
instance into a String
instance using UTF-8. init(data:encoding:)
has the following declaration:
在 Swift 5 中,您可以使用String
的init(data:encoding:)
初始化程序将Data
实例转换为String
使用 UTF-8的实例。init(data:encoding:)
有以下声明:
Returns a
String
initialized by converting given data into Unicode characters using a given encoding.
返回
String
通过使用给定编码将给定数据转换为 Unicode 字符而初始化的。
The following Playground code shows how to use it:
以下 Playground 代码展示了如何使用它:
##代码##