A. Mashreghi A. Mashreghi - 1 year ago 45
iOS Question

Where to put the text files when I distribute the app?

I have a simple application that needs to read multiple text files. But right now in order to access the files I am giving the address of the file in my laptop.

let path = "/Users/alimashreghi/Desktop/glossories/science.txt"
var text:String = ""


text = try NSString(contentsOfFile:path, encoding: NSUTF8StringEncoding) as String



Now, I am concerned about when I want to distribute the app. Where should I put the text files and how should I read them to ensure that it works properly as an app in an iPhone?

Besides, I don't know much about distributing swift apps.

// ViewController.swift
// Test
// Created by Ali Mashreghi on 2016-08-29.
// Copyright © 2016 Ali Mashreghi. All rights reserved.

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
let data = NSData.init(contentsOfFile: "/Users/TestProj/science.txt") //prints Optional(4380)
let data = NSData.init(contentsOfFile: "science.txt") //prints nil


// Do any additional setup after loading the view, typically from a nib.

override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.


enter image description here

Answer Source

Just put them in your application's bundle, then you can read them as:

NSString *filePath = [[NSBundle mainBundle] pathForResource:  "science" ofType:@"txt"];
NSData *data = [NSData dataWithContentsOfFile:filePath];


    if let filepath = Bundle.main.path(forResource: "science", ofType: "txt")
        let data = NSData.init(contentsOfFile: filepath)

You can drag and drop them into Xcode's navigation area, ensure they are included in the bundle in Xcode's Build Phases | Copy Bundles Resources.