简体   繁体   English

Swift:将字符串解码为NSData以在ImageView中显示图像

[英]Swift: Decode string to NSData to display image in ImageView

I updated XCode today. 我今天更新了XCode。 I am using XCode 6.1.1. 我正在使用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'. 错误消息是:类型'String'不符合协议'NSCopying'。

I would like to decode a String to NSData to display the image in imageView. 我想将String解码为NSData以在imageView中显示图像。 jsonDict is a NSDictionary. jsonDict是NSDictionary。 What is wrong here? 怎么了 Can anyone help? 有人可以帮忙吗?

Thanks 谢谢

The problem is jsonDict["binary"] returns an Optional (it may be nil). 问题是jsonDict["binary"]返回一个Optional (可能为nil)。 You need to unwrap it first: 您需要先将其拆开:

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

The problem here is ! 这里的问题是! in NSDataBase64DecodingOptions(rawValue: 0)! NSDataBase64DecodingOptions(rawValue: 0)! . NSDataBase64DecodingOptions 's init(rawValue:) is non Optional . NSDataBase64DecodingOptionsinit(rawValue:)是非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: 为了更好,您可以在这里使用nil

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM