ios - 在 Swift 中将 NSMutableData 转换为 NSString

标签 ios nsurlconnection swift

目前,我正在研究 Swift。

我想用 NSURLConnection 做一个小型下载器应用程序。到目前为止一切正常,但我有 2 个问题。

  1. 为什么我无法将响应数据转换为 NSString
  2. 如何将我的网络服务器 NSURLResponse 转换为 NSHTTPURLResponse

到目前为止,我的代码如下所示:

import Foundation

class Downloader: NSObject, NSURLConnectionDelegate {

    let urlString: String
    var responseData: NSMutableData = NSMutableData()
    var responseMessage: NSURLResponse = NSURLResponse()

    init(urlString: String) {
        self.urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding);
    }

    func startDownloaderWithUrl() {
        let url: NSURL = NSURL.URLWithString(self.urlString);
        let r: NSURLRequest = NSURLRequest(URL: url);
        let connection:NSURLConnection = NSURLConnection(
            request: r,
            delegate: self,
            startImmediately: true);
    }

    func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
        NSLog("Connection failed.\(error.localizedDescription)")
    }

    func connection(connection: NSURLConnection, didRecieveResponse response: NSURLResponse)  {
        NSLog("Recieved response")
        self.responseMessage = response;
    }

    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        self.responseData = NSMutableData()
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
        self.responseData.appendData(data)
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        let responseString: NSString = NSString(data: self.responseData, encoding: NSUTF8StringEncoding);

        NSLog("%@", "Finished Loading");
        //NSLog("%@", self.responseData);
        NSLog("%@", responseString);
    }
 }

虽然我的 responseData 有大量字节,但我的 responseString 总是 nil。其次,如何将我的响应消息转换为 NSHTTPURLResponse

最佳答案

试试这个

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
    self.data = NSMutableData()
}

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
    self.data.appendData(data)
}

func connectionDidFinishLoading(connection: NSURLConnection!) {
    var dta = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("the string is: \(dta)")

    }

关于ios - 在 Swift 中将 NSMutableData 转换为 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24053618/

相关文章:

swift - Swift 中具有返回类型的可选函数

swift - 将协议(protocol)<>任意转换为字符串(或其他)

ios - Apple IPv6 $http ionic 拒绝

ios - 在 iOS 中存储应用内图片的最佳选择

objective-c - Mac OSX - 如何使用 Cocoa 甚至纯 C 函数获取代理配置?

ios - 既然我们有 [NSData dataWithContentsOfURL :], 为什么我们要使用 [NSURLConnection sendSynchronousRequest :returningResponse:error:]?

ios - 将较小的音频文件从iOS应用上传到Python-Flask服务器

ios - 如果我使用 prepareForSegue 传递数据,则无法嵌入导航 Controller

ios - 如何禁用条形图的选择?

ios - Swift 无法修复 UITableView 的导航栏