我正在尝试将UIIMAGE编码为base64字符串。我的代码是:
@IBOutlet weak var photoImageView: UIImageView!
let image : UIImage = UIImage(named:"photoImageView")!
let imageData:NSData = UIImagePNGRepresentation(image)!
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
问题是我遇到了这种错误:"致命错误:在解开可选值时出乎意料地找到了无否"
我在做什么错?
prasad的评论可能是您遇到的问题。
对于任何返回选项的功能,我通常使用if - let
语法或警卫来确保我不会意外解开零包装。
if let image = UIImage(named:"photoImageView") {
if let imageData = UIImagePNGRepresentation(image) {
// swift 2
// imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
// swift 3
let strBase64:String = imageData.base64EncodedString(options: [.lineLength64Characters])
} else {
print("can't get PNG representation")
}
} else {
print("can't find photoImageView image file")
}
@enix您的评论做到了。解决我的问题是这条线
let image = photoImageView.image
正如您指出的那样,UIImage是使用图像资产初始化的,而不是图像视图