Now apple have handily gotten rid of the NSString
and String
automatic compatibility, I'm having a bit of a nightmare going between the two. I'm getting a couple of NSString
s out of a dictionary and I can't convert them to regular String
s...
I've tried:
let fileNameString: String = String(format: "%@", filename!)
let fileNameString: String = (filename as! String)
let fileNameString = filename as? String
let fileNameString = (filename as? String) ?? ""
if let fileNameString = filename as? String {
println("\(fileNameString)")
}
But all produce the error.
I've broken in at the point of conversion and can see neither NSStrings are nil:
But no joy with either. Getting Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)
. Am I missing something obvious here?
Even just trying to print the NSString filename
before conversion causes the same error..
Posting the code prior to conversion attempt to see if that has anything to do with it...
// First we create a head request as the info I need is in the headers
var newRequest: NSMutableURLRequest = NSMutableURLRequest(URL: request.URL!)
newRequest.HTTPMethod = "HEAD"
var response: NSURLResponse?
NSURLConnection.sendSynchronousRequest(newRequest, returningResponse: &response, error: nil)
// Unwrap response as httpResponse in order to access allHeaderFields
if let httpResponse = response as? NSHTTPURLResponse {
let headerString = "sfn-Document-Filename"
let headerNSString = headerString as NSString
let filetypeString = "Content-Type"
let filetypeNSString = filetypeString as NSString
// This is a dictionary where the keys are NSCFStrings
// (NSStrings, hence creating the NSStrings above)
var allHeaders = httpResponse.allHeaderFields
// Getting the filename out here only works with as? NSString. as? String creates the same error as converting.
let filename = allHeaders[headerNSString] as? NSString
// This is a string which contains the type as 'application/pdf' for example. We only need the part after the /.
// Again, trying to get this out as a String fails
let typeString = allHeaders[filetypeNSString] as? NSString
var typeArray = typeString?.componentsSeparatedByString("/") as! [NSString]
let filetype = typeArray[1]
}