Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在swift中设置另一个视图的背景_Ios_Swift_Background - Fatal编程技术网

Ios 在swift中设置另一个视图的背景

Ios 在swift中设置另一个视图的背景,ios,swift,background,Ios,Swift,Background,我想让用户为应用程序的主视图选择一个背景。 我想知道我如何在另一个视图中做到这一点,即使应用程序被终止 我曾考虑将图像的路径保存在Userdefaults中,然后从主视图获取它,但我无法从资源URL设置背景。有办法做到这一点吗?或者更好的方法 以下是我迄今为止所做的工作: @IBOutlet weak var imageView: UIImageView! var imagePicker = UIImagePickerController() @IBAction func background

我想让用户为应用程序的主视图选择一个背景。 我想知道我如何在另一个视图中做到这一点,即使应用程序被终止

我曾考虑将图像的路径保存在
Userdefaults
中,然后从主视图获取它,但我无法从
资源URL设置背景。有办法做到这一点吗?或者更好的方法

以下是我迄今为止所做的工作:

@IBOutlet weak var imageView: UIImageView!
var imagePicker = UIImagePickerController()

@IBAction func background(_ sender: Any) {
    self.imagePicker.allowsEditing = false
    self.imagePicker.sourceType = .savedPhotosAlbum

    imagePicker.modalPresentationStyle = .overCurrentContext
    self.present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

        self.imageView.contentMode = .scaleAspectFit
        let imageUrl = info[UIImagePickerControllerReferenceURL] as! URL
        UserDefaults.standard.set(imageUrl, forKey: "background")
        imageView.image = pickedImage

    }

    dismiss(animated: true, completion: nil)

}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    self.imagePicker = UIImagePickerController()
    dismiss(animated: true, completion: nil)
}

如何从viewDidLoad()中的默认值加载URL,然后调用setImageFromURL?当然,您必须将图像设置为ImageView

func setImageFromURl(stringImageUrl url: String){

      if let url = NSURL(string: url) {
         if let data = NSData(contentsOf: url as URL) {
            self.image = UIImage(data: data as Data)
         }
      }
   }

将图像数据保存到
CoreData
@sCha不知道如何使用
CoreData
。。。从来没用过。事实上。。。我想我的URL有问题。在查找我的URL时,它找不到任何内容(
nil
)。@Hawkydoky也许您必须在项目设置中允许任意加载。(如果你想发布你的应用,不推荐)@Moritz这个例子处理一个本地URL。在我看来没有必要URLSession@chris.breezy正确的。我没注意到。谢谢。最后,我用这个答案解决了这个问题。谢谢你的帮助。