You could just as easily use it to load images or any other media. This same technique can be used to load any file, not just text. The viewDidLoad() code should now look something like override func viewDidLoad() We concatenate the path and add what we know to be the file name, noting the ‘/' in front of the file name.įinally, we assign the text content to our text field. Since there is the possibility that our file does not exist or something else could go wrong we put the statement in a try block. let textContent = try! String(contentsOfFile: filePath + "/thetext.txt", encoding: NSUTF8StringEncoding) Now we try and load the contents of the file into a constant. resourcePath! gives us the full pathname to the bundle's subdirectories containing our resources which include our text file. NSBundle.mainBundle() gives us the bundle object that contains our application executable. Let's get started, for simplicity, I am going to do this in the viewDidLoad to keep only minimal code in the example.įirst, we need to get the full path to our application let filePath = NSBundle.mainBundle().resourcePath! So what is it we need to do to make it all work? That's the set-up complete, on to the coding fun. Now add a new file to the project (right-click on the project name and choose new file), This is the text file that will hold the data, I called it thetext.txt, and placed 3 paragraphs of plain text in the file. Next, Create an for the Text View object, I called mine displayText. I also removed the default text so it starts out empty. Set-Upįirst, create a single view application and add a Text View object to the storyboard. Not a massive mind-blowing demonstration, but a simple one to get the idea across. Since the sandboxing on iOS gives your application access to its own folder structure you can gain access to files in your bundle by tapping into the NSFileManager and the main bundle resource path.įor this example let's say you have some reason to read in a text file contained in your application bundle and display it on the screen. Here is a quick rundown on how you can access files within your application bundle on iOS with Swift.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |