iosiphoneswiftios-app-groupios10-today-widget

Not able to read from shared containor in app group ios


I have created an app group group.com.example.FoodTracker-qg, In the main view controller of the app I am downloading an image and storing inside the shared container but I am unable to use the same image in image view. I am getting the following error

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=256 "The file “EC700C58-E9C9-480D-8EE2-B88A570A5728image.jpg” couldn’t be opened." UserInfo={NSURL=/private/var/mobile/Containers/Shared/AppGroup/EC700C58-E9C9-480D-8EE2-B88A570A5728image.jpg}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-800.0.63/src/swift/stdlib/public/core/ErrorType.swift, line 178

Below is my code for writing and reading from shared container

//  ViewController.swift


import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var mealName: UILabel!
    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "https://static.pexels.com/photos/3247/nature-forest-industry-rails.jpg"
        try? Data(contentsOf: URL(string: urlString)!).write(to: getSharedFileUrl("image.jpg"))
        imageView.image = UIImage(data: try! Data(contentsOf: getSharedFileUrl("image.jpg")))                  
    }

    func getSharedFileUrl(_ fileName: String) -> URL {
        let fileManager = FileManager.default
        let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.example.FoodTracker-qg")
        return URL(string: url!.path.appending(fileName))!
    } 
}

Solution

  • Code seems to be correct, your problem might be due to file name itself.... check url in error

    /private/var/mobile/Containers/Shared/AppGroup/EC700C58-E9C9-480D-8EE2-B88A570A5728image.jpg

    there's no "/"...it should look like 728/image.jpg