Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file data Applications document directory in swift?

Tags:

swift

I am new at Swift programming language. I want to download a movie from some tube servers and want to play offline. I am using Alamofire for downloading part. I can list the file(s) with that:

var file:String?
if let files = NSFileManager.defaultManager().contentsOfDirectoryAtPath(documentsDirectory, error: &error) as? [String] {
                for filename in files {
                    // do stuff with filename
                    file = filename
                    println(filename)
                }
            }

But the problem is how i can use that file for my purpose. Let assume its image file and i want to show in imageview.

myImageView.image = UIImage(contentsOfFile: file) /* doesn't work*/

thank you for any help.

like image 314
Antiokhos Avatar asked Nov 01 '14 12:11

Antiokhos


People also ask

How do I read a text file in Swift?

To read a Text File in Swift, we can prepare the file url and then use String initializer init(contentsOf: url) that returns file content as a string.

How do I create a directory in Swift?

Creating a new directory A new directory is created in Swift using the createDirectory(atPath:) instance method of the FileManager class. It is once again passing through the pathname of the new directory as an argument and returning a Boolean true or false result.


2 Answers

For Swift 2 you have to change something. Note: stringByAppendingPathComponent is not more available on String (only NSString):

var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var getImagePath = paths.stringByAppendingPathComponent("filename")
myImageView.image = UIImage(contentsOfFile: getImagePath)
like image 52
Peter Kreinz Avatar answered Sep 26 '22 09:09

Peter Kreinz


Try this code:

var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var getImagePath = paths.stringByAppendingPathComponent("filename")
myImageView.image = UIImage(contentsOfFile: getImagePath)

I hope this work.

like image 32
Aditya Dharma Avatar answered Sep 25 '22 09:09

Aditya Dharma