简体   繁体   English

如何在swift中读取文件数据应用程序文档目录?

[英]How to read file data Applications document directory in swift?

I am new at Swift programming language. 我是Swift编程语言的新手。 I want to download a movie from some tube servers and want to play offline. 我想从一些电子管服务器下载电影,想要离线播放。 I am using Alamofire for downloading part. 我正在使用Alamofire下载部分。 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. 假设它的图像文件,我想在imageview中显示。

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

thank you for any help. 感谢您的任何帮助。

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. 我希望这项工作。

For Swift 2 you have to change something. 对于Swift 2,你必须改变一些东西。 Note: stringByAppendingPathComponent is not more available on String (only NSString): 注意: StringByAppendingPathComponent在String上不再可用(仅限NSString):

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

File manage is used for below functionality, Please check once. 文件管理用于以下功能,请检查一次。

1) create folder in document directory or temp directory, 1)在文档目录或临时目录中创建文件夹,

2) copy file from temp to document directory, move path, 2)将文件从temp复制到文件目录,移动路径,

3) remove from document directory, 3)从文档目录中删除,

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), 4)列出文档目录中的所有文件,使用文档目录中的扩展名列出文件(例如:如果你在文件目录中有.mp3和.jpg以及.text文件,你只需要.mp3文件),

5) save file 5)保存文件

6) get file path 6)获取文件路径

https://github.com/IosPower/FileManage https://github.com/IosPower/FileManage

At the moment you're just passing in the name of the file to UIImage(contentsOfFile). 此刻,您只需将文件名传递给UIImage(contentsOfFile)。 You need to pass in the entire path, ie: 你需要传递整个路径,即:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM