将swift4中的图像转换为base64

将swift4中的图像转换为base64,swift,image,base64,swift4,encode,Swift,Image,Base64,Swift4,Encode,我的问题是变量(image)为空,但我确信我已选择了正确的imageView只有当映像存在于资产目录中且资产目录是目标的成员时,代码才会工作 也许您只是将文件添加到项目中,而不是添加到资产目录中?在这种情况下,请尝试 let image: UIImage = UIImage(named:"imageView")! let imageData: NSData = UIImagePNGRepresentation(image)! as NSData base64String = imageData.

我的问题是变量(image)为空,但我确信我已选择了正确的imageView

只有当映像存在于资产目录中且资产目录是目标的成员时,代码才会工作

也许您只是将文件添加到项目中,而不是添加到资产目录中?在这种情况下,请尝试

let image: UIImage = UIImage(named:"imageView")!
let imageData: NSData = UIImagePNGRepresentation(image)! as NSData
base64String = imageData.base64EncodedString(options: .lineLength64Characters)
print(base64String as Any)

为什么使用php标记?是否有名为“imageView”的图像文件或资产图像集?另外,不需要强制转换到NSData,也可能需要声明
.lineLength64个字符。
guard let url = Bundle.main.url(forResource: "image", withExtension: "jpg") else {
    return
}
guard let data = try? Data(contentsOf: url) else {
    return
}
print(data.base64EncodedString())