Reputation: 8396
I am getting an error when i try to convert NSData
to NSString
in Swift
This is my request :
var request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 200)
I am getting the error here :
var mydata :NSData = NSURLCache.sharedURLCache().cachedResponseForRequest(request)!.data
var datastring = NSString(data: mydata, encoding: UInt()) as! String
My both try to get rid of the warning error but didn't work:
i increased timeoutInterval
to be 200 .
And i tried :
var myinfo = NSString(bytes: mydata.bytes, length: mydata.length, encoding: self.responseEncoding())
func responseEncoding() -> NSStringEncoding {
return responseEncoding()
}
This solution didn't work for me here : Incorrect NSStringEncoding value 0x0000 detected
Upvotes: 0
Views: 711
Reputation: 539965
UInt()
creates an integer with the value zero, so you are effectively
calling
var datastring = NSString(data: mydata, encoding: 0) as! String
But 0
is not a valid argument for the encoding parameter, you have to
replace it by a valid NSStringEncoding
, e.g. NSUTF8StringEncoding
.
Note also that the conversion can fail, so you better use optional binding instead of a forced cast:
if let datastring = NSString(data: mydata, encoding: NSUTF8StringEncoding) as? String {
} else {
// Encoding error ...
}
Upvotes: 1