2015-08-31 31 views
10

Tôi cần tải trước dữ liệu vào bảng của mìnhXem khi ứng dụng khởi chạy. Vì vậy, tôi đang sử dụng dữ liệu lõi bằng cách phân tích cú pháp tệp .csv. Tôi đang theo dõi this tutorial cho mục đích này. Đây là chức năng parseCSV tôiPhân tích cú pháp tệp CSV trong 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 
} 

đây là mẫu của tôi .csv

Rithala,Underground,Yellow Line,28.7209,77.1070 

Nhưng tôi đang nhận được một lỗi trên dòng này

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

Fatal error: Array index ra của phạm vi

tôi là gì làm sai? Làm ơn giúp tôi.

+0

Đặt điểm ngắt ngay trước dòng gây ra sự cố và sau đó in 'giá trị' trong trình gỡ lỗi bằng cách sử dụng' giá trị po'. Đối với một số lý do mảng của bạn không có nhiều điều như nó phải làm - kiểm tra những gì thực sự có nên cung cấp cho bạn một ý tưởng tại sao –

Trả lời

11

Bạn đang cố gắng phân tích các đường dẫn tập tin chứ không phải là nội dung của file

Nếu bạn thay thế

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

với:

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

sau đó mã sẽ làm việc ví dụ của bạn tập tin.

+0

thanx. giải pháp hoàn hảo –

+0

Cảm ơn bạn tốt sir. Giải quyết vấn đề của tôi. – Trip

+0

Bạn có thể cung cấp cho tôi 'parseCSV' trong Swift3 hay không. Cần khẩn trương – pkc456

0

Dựa trên lỗi và nơi xảy ra lỗi, tôi đoán rằng mảng values của bạn không có 5 phần tử như bạn nghĩ. Tôi sẽ đặt một breakpoint trên dòng đó là cho bạn một lỗi và kiểm tra biến số values của bạn và xem có bao nhiêu trong đó. Vì tệp .csv của bạn rõ ràng là 5 phần tử, nên tôi sẽ đoán có điều gì đó không ổn trong phân tích cú pháp của bạn.

+0

đây là những gì tôi nhận được khi tôi in 'giá trị' ' [(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

u có thể cho tôi một liên kết đến một hướng dẫn tốt hơn để phân tích cú pháp csv nhanh chóng không? –

Các vấn đề liên quan