目前,我正在研究 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);
}
}
虽然我的 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/