简体   繁体   中英

How can I read a json file in the Documents Directory in swift?

I have some JSON files in a sever. I download them and save them in the documents directory. But I can't read them. Here is my code:

let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
    let textFileURL = documentsPath.appendingPathComponent("resource/data/introduction")
    let fileURLString = textFileURL?.path
    if FileManager.default.fileExists(atPath: (fileURLString)!){
        print("success")
    }
    if let path = Bundle.main.path(forResource: "test" , ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            let jsonObj = JSONSerializer.toJson(data)
            print(jsonObj)
        } catch let error {
            print(error.localizedDescription)
        }
    } else {
        print("Invalid filename/path.")
    }

If you change this line:

let jsonObj = JSONSerializer.toJson(data)

to this:

let jsonObj = try JSONSerialization.jsonObject(with:data, options:JSONSerialization.ReadingOptions(rawValue:0))

The code should work. I don't know where the first line I highlighted came from - perhaps you are using a third-party library? If so, you might want to mention what you are using so that we can see all the elements that go into the code.

If you are using the standard JSON serialization library and the code was a simple typing error or something, could you also mention what the error you see is or what happens when the code doesn't work?

There are two possible cases:

A. In case you have multiple json file with the same name in your project but they are in different directories ( "Environment/production/myjsonfile.json" and "Environment/development/myjsonfile.json" ):

  • you have to specify the directory Bundle.main.path(forResource: "myjsonfile", ofType: "json", inDirectory: "Environment/production")
  • the directory "Environment" should be added as a Folder in your main bundle (App Target) and should be displayed in blue color (yellow it is when it is being added as a Group). Just delete its reference and add it again (remember to select to add it as a Folder and not as a Group)

B. In case you have only one kind of myjsonfile.json in your project , than just use Bundle.main.path(forResource: "myjsonfile", ofType: "json") and it will find it in your main Bundle (App Target).

I had the same problem, but researching and compiling information about problem solving, here I leave you my job, I hope to help.

import UIKit

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()

 //llamar metodo para descargar json
        descargar()

}

//------------------Descargar json--------------------------------------------------------  
func descargar() {

    //Create URL to the source file you want to download
    let fileURL = URL(string: "http://10.32.14.124:7098/Servicio.svc/getCentralesMovilJSON/")

    // Create destination URL
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!

    //agregar al destino el archivo
    let destinationFileUrl = documentsUrl.appendingPathComponent("centrales.json")

    //archivo existente???....................................................
    let fileExists = FileManager().fileExists(atPath: destinationFileUrl.path)

    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)

    let request = URLRequest(url:fileURL!)

    // si el archivo centrales.json ya existe, no descargarlo de nuevo y enviar ruta de destino.........................................................................
    if fileExists == true {
        print("archivo existente")
        print(destinationFileUrl  )
        //llamar metodo para parsear el json............................................
        parseo()

    }

// si el archivo centrales.json aun no existe, descargarlo y mostrar ruta de destino..........................................................................
    else{
        print("descargar archivo")

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success se ah descargado correctamente...................................
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Successfully downloaded. Status code: \(statusCode)")
                print(destinationFileUrl)
                //llamar metodo para parsear el json............................................
                self.parseo()
            }

            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }

        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
        }
        }
    task.resume()

    }}




//-----------------------------Extraer datos del archivo json----------------------------

func parseo(){

    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let destinationFileUrl = documentsUrl.appendingPathComponent("centrales.json")




    do {

        let data = try Data(contentsOf: destinationFileUrl, options: [])
        let centralArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] ?? []

        print(centralArray)


    }catch {
        print(error)
    }

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM