2015-08-31 16 views
10

Ho bisogno di precaricare i dati nel mio TableView all'avvio dell'app. Quindi sto usando i dati di base analizzando un file .csv. Sto seguendo this tutorial per questo scopo. Qui è la mia funzione parseCSVAnalisi file CSV in Swift

func parseCSV (contentsOfURL: NSURL, encoding: NSStringEncoding, error: NSErrorPointer) -> [(stationName:String, stationType:String, stationLineType: String, stationLatitude: String, stationLongitude: String)]? { 
    // Load the CSV file and parse it 
    let delimiter = "," 
    var stations:[(stationName:String, stationType:String, stationLineType: String, stationLatitude: String, stationLongitude: String)]? 

    let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error) 
    stations = [] 
    let lines:[String] = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String] 

    for line in lines { 
     var values:[String] = [] 
     if line != "" { 
      // For a line with double quotes 
      // we use NSScanner to perform the parsing 
      if line.rangeOfString("\"") != nil { 
       var textToScan:String = line 
       var value:NSString? 
       var textScanner:NSScanner = NSScanner(string: textToScan) 
       while textScanner.string != "" { 

        if (textScanner.string as NSString).substringToIndex(1) == "\"" { 
         textScanner.scanLocation += 1 
         textScanner.scanUpToString("\"", intoString: &value) 
         textScanner.scanLocation += 1 
        } else { 
         textScanner.scanUpToString(delimiter, intoString: &value) 
        } 

        // Store the value into the values array 
        values.append(value as! String) 

        // Retrieve the unscanned remainder of the string 
        if textScanner.scanLocation < textScanner.string.characters.count { 
         textToScan = (textScanner.string as NSString).substringFromIndex(textScanner.scanLocation + 1) 
        } else { 
         textToScan = "" 
        } 
        textScanner = NSScanner(string: textToScan) 
       } 

       // For a line without double quotes, we can simply separate the string 
       // by using the delimiter (e.g. comma) 
      } else { 
       values = line.componentsSeparatedByString(delimiter) 
      } 

      // Put the values into the tuple and add it to the items array 
      let station = (stationName: values[0], stationType: values[1], stationLineType: values[2], stationLatitude: values[3], stationLongitude: values[4]) 
      stations?.append(station) 
     } 
    } 


    return stations 
} 

questo è il mio campione file .csv

Rithala,Underground,Yellow Line,28.7209,77.1070 

Ma sto ottenendo un errore su questa linea

let station = (stationName: values[0], stationType: values[1], stationLineType: values[2], stationLatitude: values[3], stationLongitude: values[4]) 
      stations?.append(station) 

Fatal error: Indice della matrice fuori del range

Cosa sono io fare male? Mi aiuti per favore.

+0

Inserire un punto di interruzione appena prima della linea che causa il problema, e quindi stampare 'valori' nel debugger usando' valori po'. Per qualche ragione il tuo array non ha tante cose come dovrebbe fare - esaminare cosa c'è in realtà dovrebbe darti un'idea del perché –

risposta

11

Si sta tentando di analizzare il percorso del file piuttosto che il contenuto del file

Se si sostituisce

let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error) 

con:

if let data = NSData(contentsOfURL: contentsOfURL) { 
    if let content = NSString(data: data, encoding: NSUTF8StringEncoding) { 
    //existing code 
    } 
} 

allora il codice lavorerà per il tuo esempio file.

+0

grazie. soluzione perfetta –

+0

Grazie buon signore. Risolto il mio problema – Trip

+0

Potete fornirmi 'parseCSV' in Swift3. Ho bisogno di urgenza – pkc456

0

In base all'errore e al punto in cui si verifica l'errore, suppongo che l'array values non contenga 5 elementi come si pensa. Metterei un breakpoint sulla linea che ti sta dando un errore e ispezionare la tua variabile values e vedere quanti sono in essa. Dato che il tuo file .csv è ovviamente lungo 5 elementi, suppongo che qualcosa stia andando male durante l'analisi.

+0

questo è quello che ottengo quando stampo i valori ' ' [(file: /// Users /sumeshagarwal/Library/Developer/CoreSimulator/Devices/ED48342B-E512-41EB-88DD-50728C8BC9AF/data/Containers/Bundle/Application/1BD48658-3F83-4B41-BE83-731809E3C44B/MetroCoreData.app/stationdata.csv, 4, 0x00007fff5c189c50)] ' –

+0

puoi darmi un collegamento ad un tutorial migliore per analizzare csv in swift? –