ios - 即使从图库或相机中选择新图像后,个人资料图像也不会更新

标签 ios iphone swift xcode

大家好,提前感谢所有帮助我的人:)

我想让人们从图库中选择一张图片(比如个人资料图片)

即使退出应用程序,所选图像仍将保留... 当我回到应用程序时,我想查看我选择的图片 请问我该怎么做?

使用 Swift 4

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        @IBOutlet weak var imageView: UIImageView!

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

            imageView.backgroundColor = UIColor.lightGray
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            dismiss(animated: true, completion: nil)
        }
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
            imageView.image = image
            imageView.contentMode = .scaleAspectFill

            dismiss(animated: true, completion: nil)
        }

        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

            let controller = UIImagePickerController()
            controller.delegate = self
            controller.sourceType = .photoLibrary
            present(controller, animated: true, completion: nil)
        }
    }

最佳答案

当您选择任何图像时,您可以使用saveImage() 方法将图像保存在文档目录中。调用 getImage() 方法在 viewDidLoad 中获取图像并将其设置到 imageView。

func saveImage(_ image: UIImage) {
    let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Profile.jpg")

    let imageData = UIImageJPEGRepresentation(image, 0.8)
    try? imageData?.write(to: url!)
}

func getImage() -> UIImage? {
    let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Profile.jpg")

    if let data = try? Data(contentsOf: url!) {
        return UIImage(data: data)
    }
    return nil
}

关于ios - 即使从图库或相机中选择新图像后,个人资料图像也不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49686402/

相关文章:

iphone - 关闭 GameKit 模态视图

ios - 从 Swift 的 UIWebView 中的 url 获取查询字符串参数?

arrays - 如何在 Swift 4 中将金字塔类型的字符串转换为 double 组

ios - Swift 2.0 中的协议(protocol)扩展方法分派(dispatch)

ios - 如何使用 EarlGrey 中的辅助功能 ID 从 UI 标签/文本字段捕获文本值?

ios - ARC的语义问题

iphone - Objective-C:如何从 0.123 或一般的 xyz... 从 0.xyz... 获得 123?

iphone - 更新 iPhone 应用程序没有推送给我

ios - View Controller 之间的一类实例化快速共享

iphone - 当 dispatchPeriod 与 Google Analytics 一起使用时,我可以立即/手动调度事件吗?