8

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.

1
  • What do you mean by "doesn't work"? What do you expect to happen? What actually happens? Commented Nov 2, 2014 at 17:44

4 Answers 4

8

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)
Sign up to request clarification or add additional context in comments.

Comments

6

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.

1 Comment

How do it with mp3 files? Please help me
0

File manage is used for below functionality, Please check once.

1) create folder in document directory or temp directory,

2) copy file from temp to document directory, move path,

3) remove from document directory,

4) list all file from document directory, list file using extension from document directory (ex: if you have .mp3 and .jpg and .text files in document directory and you want only .mp3 file),

5) save file

6) get file path

https://github.com/IosPower/FileManage

Comments

-4

At the moment you're just passing in the name of the file to UIImage(contentsOfFile). You need to pass in the entire path, i.e.:

myImageView.image = UIImage(contentsOfFile: "\(documentsDirectory!)/\(filename)")  //hopefully does work!

2 Comments

Yuk! Hardcoding the document directory name and using string paths instead of file URLs.
Hi @Abizern I wasn't suggesting hardcoding the documentsDirectory - it's already being stored in a variable. Could you explain your suggestion further?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.