我正在创建一个应用来捕获照片并将其与一些UITextField
数据一起保存。
我已使用核心数据存储UITextField
数据并且工作正常,但我无法使用核心数据保存图像。
我已拍摄照片并将该照片伪装到下一个视图控制器进行预览,然后从那里我需要保存并转到家庭视图控制器,以在UITextField
中显示包含相关UITableViewCell
数据的图片。< / p>
UITextField
保存和获取UITableViewCell
但无法保存和获取图片,一切正常。
答案 0 :(得分:1)
如果你仍然在努力弄清楚这里是代码片段,祝你好运
func saveImageToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = "image001.png" // name of the image to be saved
let fileURL = documentsDirectory.appendingPathComponent(fileName)
if let data = UIImageJPEGRepresentation(image, 1.0),!FileManager.default.fileExists(atPath: fileURL.path){
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}
func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
let image = UIImage(contentsOfFile: imageURL.path)
return image!
}
return UIImage.init(named: "default.png")!
}
答案 1 :(得分:0)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myimageview: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
getSaveImage()
}
func getSaveImage()
{
let document = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
print("Document :\(document)")
let imgurl = document.appendingPathComponent("img1", isDirectory: true)
print("Image Url : \(imgurl.path)")
if !FileManager.default.fileExists(atPath: imgurl.path)
{
do{
try UIImage(named: "img1")!.jpegData(compressionQuality: 0.75)!.write(to: imgurl)
print("image save")
}
catch{
print("image not save")
}
}
myimageview.image = UIImage(contentsOfFile: imgurl.path)
}
}