【发布时间】:2014-06-05 06:58:43
【问题描述】:
目前,我正在玩 Swift。
我想用NSURLConnection 做一个小型下载应用程序。到目前为止一切正常,但我有 2 个问题。
- 为什么我无法将我的响应数据转换为
NSString? - 如何将我的网络服务器
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);
}
}
我的responseString 始终是nil,尽管我的responseData 有大量字节。其次,如何将我的回复消息转换为NSHTTPURLResponse?
【问题讨论】:
-
我认为你的实现是正确的,检查编码而不是,试试
NSASCIIStringEncoding -
好吧,这是我使用的错误编码。 NSASCIIStringEncoding 按预期工作。但我确信 NSUTF8String 编码在以前的纯 Objective-C 项目中对我有用。也许你知道如何将 NSURLRepsonse 转换为 NSHTTPURLResponse?我认为它必须看起来像这样
var urlRsponse = self.responseMessage as NSHTTPURLResponse?
标签: ios nsurlconnection swift