2016-12-15 93 views
0

我想將UIImage編碼爲base64字符串。我的代碼是這樣的:UIImage視圖編碼爲base64

@IBOutlet weak var photoImageView: UIImageView! 

let image : UIImage = UIImage(named:"photoImageView")! 
let imageData:NSData = UIImagePNGRepresentation(image)! 
let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) 

的問題是,我得到這樣的錯誤:「致命錯誤:意外發現零而展開的可選值」

我在做什麼錯?

+0

這行你得到這個錯誤? – Enix

+0

這一個:讓圖像:UIImage = UIImage(命名爲:「photoImageView」)! – markan3

+1

確保您已將「photoImageView」添加到項目中,檢查拼寫,大寫,小寫。 – prasad

回答

0

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") 
} 
0

@Enix您的評論做了詭計。解決我的問題是這條線

let image = photoImageView.image 

正如你指出的UIImage被初始化與圖像資產,不具有圖像視圖