How to fetch data from 2 csv files in swift -
my app gets data (points on map) .csv file san francisco.
what should change in code data san francisco oakland, .csv file have added?
func setupdata() { pointsdatasource = pointsdatasource(with: "san francisco") //if let pointsdatasource = pointsdatasource { //map.addannotations(pointsdatasource.annotations) //} }
there few different methods scanning csv file app using swift. found able create own class method thought useful.
i have apologise because haven't referenced internet posts other developers helped me out - if come accross them again i'll include them!
here class:
import foundation class csvscanner { class func debug(string:string){ println("csvscanner: \(string)") } class func runfunctiononrowsfromfile(thecolumnnames:array<string>, withfilename thefilename:string, withfunction thefunction:(dictionary<string, string>)->()) { if let strbundle = nsbundle.mainbundle().pathforresource(thefilename, oftype: "csv") { var encodingerror:nserror? = nil if let fileobject = nsstring(contentsoffile: strbundle, encoding: nsutf8stringencoding, error: &encodingerror){ var fileobjectcleaned = fileobject.stringbyreplacingoccurrencesofstring("\r", withstring: "\n") fileobjectcleaned = fileobjectcleaned.stringbyreplacingoccurrencesofstring("\n\n", withstring: "\n") let objectarray = fileobjectcleaned.componentsseparatedbystring("\n") anobjectrow in objectarray { let objectcolumns = anobjectrow.componentsseparatedbystring(",") var adictionaryentry = dictionary<string, string>() var columnindex = 0 anobjectcolumn in objectcolumns { adictionaryentry[thecolumnnames[columnindex]] = anobjectcolumn.stringbyreplacingoccurrencesofstring("\"", withstring: "", options: nsstringcompareoptions.caseinsensitivesearch, range: nil) columnindex++ } if adictionaryentry.count>1{ thefunction(adictionaryentry) }else{ csvscanner.debug("no data extracted row: \(anobjectrow) -> \(objectcolumns)") } } }else{ csvscanner.debug("unable load csv file path: \(strbundle)") if let errorstring = encodingerror?.description { csvscanner.debug("received encoding error: \(errorstring)") } } }else{ csvscanner.debug("unable path csv file: \(thefilename).csv") } } }
you can implement in code this:
var mycsvcontents = array<dictionary<string, string>>() csvscanner.runfunctiononrowsfromfile(["title", "body", "category"], withfilename: "filename.csv", withfunction: { (arow:dictionary<string, string>) in mycsvcontents.append(arow) })
this build array of dictionary objects, each representing row csv. need supply array first parameter contains header labels of csv document - make sure include label every column!
however, feel free skip adding rows array - can run function on each row. instance, may want add these directly coredata object.
Comments
Post a Comment