Esat kemal Ekren
Esat kemal Ekren

Reputation: 556

Read Local Text File in Swift IOS

I have data in text format and that text format is located in my app local file. I did my research but I couldn't find anything about it. How to read that text file in swift? Should i use Sqlite or normal text file format with NSBundle? I hope someone help me to start something with.

Upvotes: 1

Views: 1726

Answers (2)

empedocle
empedocle

Reputation: 1932

The following will place the contents of the file into a string:

let filePath = NSBundle.mainBundle().pathForResource("file", ofType: "txt");
let fileData = String(filePath!, encoding:NSUTF8StringEncoding, error:nil)!

Upvotes: 2

Anand
Anand

Reputation: 32

var filePath  = NSBundle.mainBundle().pathForResource("world_country_state", ofType:"json")
        var nsMutData = NSData(contentsOfFile:filePath!)
        var sJson     = NSJSONSerialization.JSONObjectWithData(nsMutData!, options: .MutableContainers, error: nil) as! NSMutableDictionary
        let arraycOuntry: NSArray = sJson.valueForKey("world")?.allKeys as! NSArray
        let states: NSArray = sJson.valueForKey("world")?.valueForKey("USA") as! NSArray

pickerDataSoruce = states.mutableCopy() as! NSMutableArray

In this Code world_country_state.json is My File just You replace your file name.
i think this Code is very helpful for you.

Upvotes: -1

Related Questions