Search code examples
iosswift4

How to use photo from photo library ios every time the apps loads?


im trying to do the follow : user is picking image from photo lib as profile pic -> from now on this image will use as profile pic even if the app closed .

im using this code :

        if let imageUrl = info[UIImagePickerController.InfoKey.referenceURL] as? NSURL { 
          // how can i get the pic url that i can use it when the app is starting ? 
        }

this is the way i loading photos right now : ( the path is taken from assets )

var img = UIImage(named:getAvatarPath());

btw im using swift 4 .

thanks .


Solution

  • You can save the image name or URL to UserDefaults.
    Here is a code snippet to save URL string to UserDefaults.

    UserDefaults.standard.set(avatarUrl, forKey: "userAvatar")  
    

    And retrieve the URL when displaying the image.
    Something like this:

    UserDefaults.standard.object(forKey: "userAvatar") as? String
    

    You can also create a property in a class or struct by combining the above approaches to save/retrieve a property to/from UserDefaults.
    for example:

    var userAvatar = UserDefaults.standard.object(forKey: "userAvatar") as? String {
        didSet {
            UserDefaults.standard.set(avatarUrl, forKey: "userAvatar")
        }
    }
    

    Now you can use this property to save or load the image URL string using UserDefaults.

    Hope this helps