0

I'm reading a .txt file in iOS/Swift. I get all my information from the text file. The problem is I only want to get the usernames and store them in an array. Right now I think it's storing all my data from .txt file in a string. How can I parse this correctly so I have only the usernames in an array?

Here is my code right now

    if let filepath = NSBundle.mainBundle().pathForResource("myfile", ofType: "txt") {
        do {
            let contents = try NSString(contentsOfFile: filepath, usedEncoding: nil) as String
            print(contents)
        } catch {
            // contents could not be loaded
        }
    } else {
        print("UNABLE TO FIND TEXT FILE");
    }

My text File Format:

User FirstName LastName

asf john smith

adfkh carrie underwood

Yusha
  • 53
  • 7
  • 2
    If this is a fixed file you wish to supply with your app, it would be easier if you put all the data into a plist file. Then you can load the plist file directly into an array. – rmaddy Apr 16 '16 at 23:19
  • 2
    What does the text file look like? – Tim Vermeulen Apr 16 '16 at 23:26
  • 1
    We can't possibly help you unless you tell us the format of your text. rmaddy's suggestion of using a plist is good. That way you can read the file directly into native iOS data structures like arrays, dictionaries, strings, integers, etc. – Duncan C Apr 16 '16 at 23:35
  • Ill update the OP with the text file format, sorry about that – Yusha Apr 16 '16 at 23:43
  • Ok check my updated post with the text file format. – Yusha Apr 16 '16 at 23:45
  • You're looking for `split()` and there are good details here: http://stackoverflow.com/questions/25678373/swift-split-a-string-into-an-array – user212514 Apr 16 '16 at 23:55

2 Answers2

0

Here is a solution using high order functions. Hopefully this works for you.

let text = "tj thomas jeffereson \nbf benjamin franklin\ngw george washington"


let usernames = text.characters
    .split { $0 == "\n" }
    .map { String($0) }
    .map { String($0.characters.split(" ")[0]) }

print(usernames)

output:

["tj", "bf", "gw"]

Loop through result:

for user in usernames {
   print(user)
}
ryantxr
  • 4,119
  • 1
  • 11
  • 25
0

Edit: Add solution by using .plist file

One way, you can store the information into a .plist file.

  1. Press command+N to add a new .plist file with name of UserInformation.plist (You can replace UserInformation with any name you like.) and edit it as below

enter image description here

  1. Then you can store user name into a array.

    if let path = NSBundle.mainBundle().pathForResource("UserInformation", ofType: "plist") {
        if let data = NSArray(contentsOfFile: path) {
            let userName = NSMutableArray.init(capacity: 1)
            for dict in data {
                userName.addObject(dict.valueForKey("User")!)
            }
            // Now user names are stored into a array
        }
    }
    

Another way, you can also store the information into a local .json file though JSON is usually used in communication between client and server.

Form iOS5, Apple provided APIs to support parse JSON.

  1. Use any text editor you like to create a json file with content below and save it with name UserInfo.json (You can replace UserInfo with any name you like.)

    [
        { "User":"asf", "FirstName":"john", "LastName":"smith"},
        { "User":"adfkh", "FirstName":"carrie", "LastName":"underwood"}
    ]
    
  2. Add it to your project.

  3. Now you can store the user name into a array.

    if let path = NSBundle.mainBundle().pathForResource("UserInfo", ofType: "json") {
        if let data = NSData(contentsOfFile: path) {
            do {
                let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers ) as! NSMutableArray
                let userName = NSMutableArray.init(capacity: 1);
                for  dict in jsonData {
                    userName.addObject(dict.valueForKey("User")!)
                }
                // Now user names are stored into a array
            } catch {
                // report error
            } 
        }
    }
    

For more details about JSON, you can visit www.json.org.

Cokile Ceoi
  • 1,326
  • 2
  • 15
  • 26