2

I have a local json file and I access the file path with Bundle.main.path function, but I get an error. enter image description here

Service

class Service {
    
    fileprivate var baseURL: String?
    
    init(baseURL: String) {
        self.baseURL = baseURL
    }
    
    func getAllData() {
        AF.request(self.baseURL!, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil, interceptor: nil, requestModifier: .none).response { (responseData) in
            guard let data = responseData.data else { return }
            do {
                let packages = try JSONDecoder().decode(Package.self, from: data)
                print(packages)
            } catch let error {
                print(error.localizedDescription)
            }
        }
    }
}

View Controller

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        guard let url = Bundle.main.path(forResource: "packageList", ofType: "json") else { return }
        
        let service = Service(baseURL: url)
        service.getAllData()
    }
Ufuk Köşker
  • 1,288
  • 8
  • 29

1 Answers1

1

You are passing a path (a String), so the URLConvertible on String, will call a URL(string: path), which will be invalid in the end, but to make it work, it would need to call URL(fileURLWithPath: path) instead.

guard let url = Bundle.main.path(forResource: "packageList", ofType: "json") else { return }

=>

guard let url = Bundle.main.url(forResource: "packageList", withExtension: "json") else { return }

OR

guard let path = Bundle.main.path(forResource: "packageList", ofType: "json") else { return }
let url = URL(fileURLWithPath: path)`

But I'd prefer the first solution, let's avoid a manual conversion.

Larme
  • 24,190
  • 6
  • 51
  • 81