目前,我正在玩Swift。
我想使用NSURLConnection
制作一个小型下载器应用程序。到目前为止,一切正常,但是我有两个问题。
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
? 最佳答案
尝试tis
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)")
}