SWIFT: NSURLSession convert data to String

前端 未结 2 942
臣服心动
臣服心动 2021-01-06 01:50

In my iPhone application (develops in SWIFT) I\'ve got to communicate with a https service (with parameters) and needs to analyse the response.

All works ok but in s

2条回答
  •  不思量自难忘°
    2021-01-06 02:08

    NSASCIIStringEncoding is documented as a strict 7-bit encoding for the ASCII values 0 .. 127. However, experiments show that when decoding NSData to (NS)String, it accepts arbitrary data and interprets the bytes 0 .. 255 as the Unicode characters U+0000 .. U+00FF. So when decoding, NSASCIIStringEncoding behaves identically to NSISOLatin1StringEncoding:

    let bytes = (0 ..< 256).map { UInt8($0) }
    let data = NSData(bytes: bytes, length: bytes.count)
    
    let s1 = String(data: data, encoding: NSASCIIStringEncoding)!
    let s2 = String(data: data, encoding: NSISOLatin1StringEncoding)!
    print(s1 == s2) // true
    

    This can explain why a character like "£" is decoded correctly even if it is not in the ASCII character set.

    But note that this behavior is (as far as I know) not documented, so you should not rely on it. Also this does not work when encoding (NS)String to NSData:

    let d1 = s1.dataUsingEncoding(NSASCIIStringEncoding) // nil
    

    If the server sends a HTTP response header with a Content-Type = charset=... field then you can detect the encoding automatically, see https://stackoverflow.com/a/32051684/1187415.

    If the server does not send the response encoding in the HTTP response header then you can only try different encodings. Frequently used encodings are

    • NSUTF8StringEncoding for the UTF-8 encoding,
    • NSWindowsCP1252StringEncoding for the Windows-1252 encoding,
    • NSISOLatin1StringEncoding for the ISO-8859-1 encoding.

    There is also a NSString method which can detect the used encoding, however this requires that you write the data to a file first, see Convert TXT File of Unknown Encoding to String.

提交回复
热议问题