SWIFT:NSURLSession将数据转换为String [英] SWIFT: NSURLSession convert data to String

查看:290
本文介绍了SWIFT:NSURLSession将数据转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的iPhone应用程序中(在SWIFT中开发)我必须与https服务(带参数)进行通信,并需要分析响应。

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

所有工作好但是在某些情况下注意到它没有得到预期的结果...进一步分析我发现将服务器响应数据转换为字符串(NSData - > NSString)的问题......

All works ok but in some cases noticed it does NOT getting the expected result... Further analysing I found it's the problem about converting server respone data to string (NSData -> NSString)...

1)。当我使用 UTF8 编码时,我将nil转换为String(responseString)

1). When I use UTF8 Encoding I am getting nil as converted String (responseString )

    let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)

2)。但是使用 ASCII 编码它很好(获取正确的响应服务器提供)

2). But with ASCII encoding it's fine (Gets the correct response server provides)

    let responseString = NSString(data: data, encoding: NSASCIIStringEncoding)

以下是我正在尝试的完整示例代码 ...

    let myUrl = NSURL(string: "https://myurl.com/myservice.asp")
    let request = NSMutableURLRequest(URL: myUrl!)

    request.HTTPMethod = "POST"
    request.timeoutInterval = 55.0
    let postString = "paramone=\(para1)&paramtwo=\(para2)&paramthree=\(para3)"

    // NOTE: Works ok with ASCII AND UTF8 both encoding types at this point...
    // request.HTTPBody = postString.dataUsingEncoding(NSASCIIStringEncoding)
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in

        if (error != nil)
        {
            println("Error: \(error)")
            println("Description: \(error.description)")
            println("Domain     : \(error.domain)")
            println("Error code : \(error.code)")
        }
        else
        {
            //???? => ENCODING PROBLEM
            // let responseString = NSString(data: data, encoding: NSASCIIStringEncoding)
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)

            println("Response: \(responseString)")
        }
    }
    task.resume()

我遇到了其他一些帖子解释相同的问题...但不确定使用ASCII而不是UTF8是否合适......

I came across with few other POSTS explaining the same issue... But NOT sure if it's good to go with ASCII rather than UTF8...

此外我无法理解响应包含'£'符号并且可以使用ASCII编码(尽管'''不是ASCII字符集),但不是UTF8。

Also I can't understand the response contains '£' sign and works ok with ASCII encoding (eventhough '£' is NOT in ASCII character Set), BUT NOT with UTF8.

喜欢听我是不是遗失任何东西或最好的方式去...谢谢。

Like to hear if I am missing anything or what the best way to go with this... Thanks.

推荐答案

NSASCIIStringEncoding 记录严格的7位编码
为ASCII值0 .. 127.然而,实验表明当
解码 NSData (NS)String ,它接受任意数据,
将字节0 .. 255解释为Unicode字符U + 0000 .. U + 00FF。
所以当解码时, NSASCIIStringEncoding 的行为与
相同 NSISOLatin1StringEncoding

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

这可以解释为什么像即使
不在ASCII字符集中,£也会正确解码。

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

但请注意,此行为(据我所知)并非记录,因此不应该依赖它。编码
(NS)字符串 NSData

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

如果服务器发送带有内容的HTTP响应头-Type = charset = ... 字段然后您可以自动检测编码,
请参阅 https ://stackoverflow.com/a/32051684/1187415

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.

如果服务器未在HTTP响应中发送响应编码
标头那么你只能尝试不同的编码。经常使用
编码

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.

还有一个 NSString 可以检测使用的
编码的方法,但是这需要先将数据写入文件,
参见将未知编码的TXT文件转换为字符串

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.

这篇关于SWIFT:NSURLSession将数据转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆