csv - Grab array components from string created from text file using Swift 2.0 -
i have text file in following format (abbreviated below):
title";"seriesid";"channelname title1";"00000001";"channel1 title2";"00000002";"channel2 title3";"00000003";"channel3 ... title99999999";"99999999";"channel99999999
i have loaded text file resource in xcode 7 , parsing follows:
class tvseriestableviewcontroller: uitableviewcontroller { var seriesdict = [string:string]() var seriesarray = nsmutablearray() override func viewdidload() { super.viewdidload() let path = nsbundle.mainbundle().pathforresource("series", oftype: "txt") let filemgr = nsfilemanager.defaultmanager() if filemgr.fileexistsatpath(path!) { { let fulltext = try string(contentsoffile: path!, encoding: nsutf8stringencoding) let readings = fulltext.componentsseparatedbystring("\n") [string] in 1..<readings.count { let seriesdata = readings[i].componentsseparatedbystring("\";\"") seriesdict["title"] = "\(seriesdata[0])" seriesdict["seriesid"] = "\(seriesdata[1])" seriesdict["channelname"] = "\(seriesdata[2])" seriesarray.addobject(seriesdict) } element in seriesarray { print(element) } } catch let error nserror { print("error: \(error)") } } self.title = "tv series" } }
for reason, above script throws index out of range error, if switch
seriesdict["title"] = "\(seriesdata[0])" seriesdict["seriesid"] = "\(seriesdata[1])" seriesdict["channelname"] = "\(seriesdata[2])"
to
seriesdict["title"] = "\(seriesdata[0])" seriesdict["seriesid"] = "\(seriesdata[0])" seriesdict["channelname"] = "\(seriesdata[0])"
there no error. have been trying figure out why can't seem access second , third component of seriesdata. after debugging, have noted seriesdata structured follows:
["title1", "00000001", "channel1"] ["title2", "00000002", "channel2"] ["title3", "00000003", "channel3"] [...] ["title99999999", "99999999", "channel99999999"]
i new xcode/swift appreciated (along explanation why above failing. thanks!
i gonna guess problem xcode didn't add "series.txt" file project's copy bundle resources. click on blue project icon in navigation view on left panel of interface. (it should @ top).
(icon highlighted in blue). after clicking that, go build phases (the tab blue lettering)
and @ bottom of view click copy bundle resources press plus , add series.txt file
doing add series.txt file main bundle , make accessible via nsbundle.mainbundle().pathforresource("series", oftype: "txt")
hope help! :d
Comments
Post a Comment