1

I have an image stored inside an AppGroup, but I'm unable to show the image and I'm not sure why.

I have this inside my view:

Image(uiImage: getImageFromDir(imageName: name)!)
   .resizable()

I get the image using the following function:

func getImageFromDir(imageName: String) -> UIImage? {
  
  let appGroupPath = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.myId")!
  
  let imagePath = appGroupPath.appendingPathComponent(imageName)
  do {
    let imageData = try Data(contentsOf: imagePath)
    return UIImage(data: imageData)
  } catch {
    print("Error loading image : \(error)")
  }
  return nil
}

This runs fine and the catch block is never hit, but the image still isn't visible. My initial thought was that I had an invalid path, but this doesn't seem the case since I can load the image as expected in React Native using the path.

There's also nothing wrong with my styles since a different image loaded from Assets.xcassets works fine.

2 Answers 2

2

Assuming the file is really existed at specified location (you can verify generated URL for that) try with security scoped resource wrapper, like below

func getImageFromDir(imageName: String) -> UIImage? {
  
  let appGroupPath = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.myId")!
  
  let imagePath = appGroupPath.appendingPathComponent(imageName)
  do {
    if imagePath.startAccessingSecurityScopedResource() {  // << this !!
        defer {
            imagePath.stopAccessingSecurityScopedResource()   // << and this !!
        }
         let imageData = try Data(contentsOf: imagePath)
         return UIImage(data: imageData)
        }
  } catch {
    print("Error loading image : \(error)")
  }
  return nil
}
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, imagePath.startAccessingSecurityScopedResource() returns false.
I can also absolutely confirm that the path to the file is right. When viewing the data of imageData and clicking Export -> save as myimage.jpg, I can sucessfully open the image in finder.
0

While my solution is working, it is NOT a valid answer to why my images aren't showing and I would still like to know why, if anyone knows who comes across this post in the future.

To solve this, instead of using an absolute path to the image, I used a base64 string to use as the data. The image now succesfully shows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.