目前,我正在玩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
?
答案 0 :(得分:3)
试试
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)")
}
答案 1 :(得分:0)
将NSMutableData转换为字符串
var YourSting = NSString(data responseData: NSData!, encoding encoding: UInt)
答案 2 :(得分:0)
将编码更改为ASCII对我有用。