[英]Convert NSMutableData to NSString in Swift
Currently, I am playing around with Swift. 目前,我正在玩Swift。
I wanted to do a small downloader app with NSURLConnection
. 我想用NSURLConnection
做一个小型下载器应用程序。 So far everything works fine, but I have 2 questions. 到目前为止一切正常,但我有2个问题。
NSString
? 为什么我无法将响应数据转换为NSString
? NSURLResponse
to NSHTTPURLResponse
? 如何将我的websever NSURLResponse
转换为NSHTTPURLResponse
? So far my code looks like this: 到目前为止我的代码看起来像这样:
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);
}
}
My responseString
is always nil
although my responseData
has a significant amount of bytes. 我responseString
永远是nil
,虽然我的responseData
具有字节显著量。 Second how can I convert my response message to NSHTTPURLResponse
? 其次,如何将我的响应消息转换为NSHTTPURLResponse
?
try 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)")
}
将NSMutableData转换为String
var YourSting = NSString(data responseData: NSData!, encoding encoding: UInt)
将编码更改为ASCII对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.