Why my return is nil but if i press the url in chrome/safari, i can get data?

前端 未结 2 1776
粉色の甜心
粉色の甜心 2020-11-27 08:27
@IBAction func mainButtonnBeTapped(sender: AnyObject) {
        let session = NSURLSession.sharedSession()
        let request = NSURLRequest(URL: NSURL(string: \"ht         


        
相关标签:
2条回答
  • 2020-11-27 09:10

    The text you try to get is probably not UTF-8, try with another encoding, like this for example:

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

    Update: read Martin R's answer for how to find the right encoding.

    0 讨论(0)
  • 2020-11-27 09:15

    This HTTP server sends a

    Content-Type = application/x-javascript; charset=GBK
    

    header field in the response, therefore you get the correct encoding from the textEncodingName property of the NSURLResponse. This can be converted to a NSStringEncoding.

    This is just a translation of the solution presented in https://stackoverflow.com/a/19885463/1187415 to Swift, plus some simple error checking:

    let session = NSURLSession.sharedSession()
    let request = NSURLRequest(URL: NSURL(string: "http://hq.sinajs.cn/list=sz000609")!)
    let task = session.dataTaskWithRequest(request, completionHandler: {
        (data, response, error) -> Void in   
    
        var usedEncoding = NSUTF8StringEncoding // Some fallback value
        if let encodingName = response.textEncodingName {
            let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
            if encoding != UInt(kCFStringEncodingInvalidId) {
                usedEncoding = encoding
            }
        }
        if let myString = NSString(data: data, encoding: usedEncoding) {
            println("this is my string: \(myString)")
        } else {
            println("failed to decode data")
        }
    })
    task.resume()
    

    Output:

    this is my string: var hq_str_sz000609="绵世股份, ....
    

    Minor changes are necessary for Swift 2:

    let session = NSURLSession.sharedSession()
    let request = NSURLRequest(URL: NSURL(string: "http://hq.sinajs.cn/list=sz000609")!)
    let task = session.dataTaskWithRequest(request, completionHandler: {
        (data, response, error) -> Void in   
    
        var usedEncoding = NSUTF8StringEncoding // Some fallback value
        if let encodingName = response?.textEncodingName {
            let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
            if encoding != UInt(kCFStringEncodingInvalidId) {
                usedEncoding = encoding
            }
        }
        if let myString = String(data: data!, encoding: usedEncoding) {
            print("this is my string: \(myString)")
        } else {
            print("failed to decode data")
        }
    })
    task.resume()
    

    Update for Swift 3:

    let session = URLSession.shared
    let request = URLRequest(url: URL(string: "http://hq.sinajs.cn/list=sz000609")!)
    let task = session.dataTask(with: request, completionHandler: {
        (data, response, error) -> Void in
    
        guard let data = data else { return }
    
        var usedEncoding = String.Encoding.utf8 // Some fallback value
        if let encodingName = response?.textEncodingName {
            let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString))
            if encoding != UInt(kCFStringEncodingInvalidId) {
                usedEncoding = String.Encoding(rawValue: encoding)
            }
        }
        if let myString = String(data: data, encoding: usedEncoding) {
            print("this is my string: \(myString)")
        } else {
            print("failed to decode data")
        }
    })
    task.resume()
    
    0 讨论(0)
提交回复
热议问题