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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With