masterWN
masterWN

Reputation: 85

Swift: Decode string to NSData to display image in ImageView

I updated XCode today. I am using XCode 6.1.1. After updating I get an error with this line.

let decodedData = NSData(base64EncodedString: jsonDict["binary"] as NSString, options: NSDataBase64DecodingOptions(rawValue: 0)!)

The error message is: Type 'String' does not conform to protocol 'NSCopying'.

I would like to decode a String to NSData to display the image in imageView. jsonDict is a NSDictionary. What is wrong here? Can anyone help?

Thanks

Upvotes: 0

Views: 560

Answers (2)

rintaro
rintaro

Reputation: 51911

The problem here is ! in NSDataBase64DecodingOptions(rawValue: 0)!. NSDataBase64DecodingOptions's init(rawValue:) is non Optional.

@availability(iOS, introduced=7.0)
struct NSDataBase64DecodingOptions : RawOptionSetType {
    init(_ rawValue: UInt)
    init(rawValue: UInt)

So you don't need ! here. To be more better, you can use just nil here:

NSData(base64EncodedString: jsonDict["binary"] as NSString, options: nil)

Upvotes: 0

Marcos Crispino
Marcos Crispino

Reputation: 8218

The problem is jsonDict["binary"] returns an Optional (it may be nil). You need to unwrap it first:

if let str: String = jsonDict["binary"] {
    let decodedData = NSData(base64EncodedString: str, options: NSDataBase64DecodingOptions(0))
}

Upvotes: 1

Related Questions