Hawkydoky
Hawkydoky

Reputation: 194

Set background of another view in swift

I'd like to let the user chose a background for the main view of the app. I'd like to know how I can do that for another view, even if the app is killed.

I thought about saving the path of the image in Userdefaults and then get it from the main view, but I'm not able to set the background from an asset URL. Is there a way to do this ? Or a better way maybe ?

Here is what I've done so far:

@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)
}

Upvotes: 1

Views: 143

Answers (1)

chris.breezy
chris.breezy

Reputation: 31

How about loading URL from defaults in viewDidLoad() and then call setImageFromURL? Of course you have to set the image to your 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)
         }
      }
   }

Upvotes: 3

Related Questions