2016-10-31 9 views
1

私はいくつかのJSONファイルをサーバーに持っています。私はそれらをダウンロードし、ドキュメントディレクトリに保存します。しかし私はそれらを読むことができません。これに文書ディレクトリ内のjsonファイルを迅速に読み取るにはどうすればよいですか?

let jsonObj = JSONSerializer.toJson(data) 

:コードは動作するはずです

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

この行を変更した場合

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.") 
    } 
+0

? – Vyacheslav

+0

'JSONSerializer'とは何ですか、それはあなたですか、またはライブラリですか?詳細と文脈を与えてください。 – Moritz

+0

"無効なファイル名/パスです。" – Humyl

答えて

0

: はここに私のコードです。私が強調した最初の行がどこから来たのか分かりません。おそらくサードパーティ製のライブラリを使用していますか?もしそうなら、使用しているものについて言及して、コードに入るすべての要素を見ることができます。

標準のJSONシリアライゼーションライブラリを使用していて、コードがシンプルなタイピングエラーだった場合は、表示されているエラーの内容や、コードが機能しないときの状況についても言えますか?

+0

が存在しますが、ファイルが存在しません – Humyl

+0

ファイルが存在しない場合は、ファイルのダウンロードと保存に関する問題が考えられます。あなたは言及した場所に静的なファイルを置いてみて、あなたのコードをテストしようとしましたか?または、最初に処理するファイルがないという問題はありますか? – Fahim

+0

Bundle.main.path(forResource: "resource/data/introduction"、ofType: "json" = nil。 – Humyl

-1

私は同じ問題を抱えていましたが、問題解決に関する情報の調査と編集を行いました。私はあなたの仕事を残しています。あなたのアプリを表示します何

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) 
    } 

} 

}

+0

テキストを英語に変更してください。 – Catalyst

関連する問題