在阵列夫特存储的文件名 [英] Storing file names in an array Swift

查看:240
本文介绍了在阵列夫特存储的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找的code,让我扫描在我的项目文件夹,并存储所有文件名称在一个阵列.jpg扩展名。
这是code我必须扫描我的X code项目的主文件夹,但是我怎么保存的文件发现里面的名字,一个数组中?

 让文件管理器:=的NSFileManager的NSFileManager()
让文件= filemanager.enumeratorAtPath(NSHomeDirectory())
而让文件=文件?.nextObject(){
    //存储所有的文件名与阵列扩展名(JPG)
}


解决方案

下面是它如何工作的例子。该函数返回的所有文件的URL数组目录中的及其所有子目录的从给定路径。

  FUNC文件(络基:字符串) -  GT; [NSURL] {
    VAR的网址:[NSURL] = []
    让dirUrl = NSURL(fileURLWithPath:络基)
    如果dirUrl!= {为零
        让文件管理器= NSFileManager.defaultManager()
        让调查员:NSDirectoryEnumerator? = fileManager.enumeratorAtURL(dirUrl!includingPropertiesForKeys:无,选择:无,的ErrorHandler:无)
        而让URL =枚举?.nextObject()作为! NSURL? {
            如果url.lastPathComponent ==.DS_Store{
                继续
            }
            urls.append(URL)
        }
    }
    返回的网址
}
让allFiles =文件(/ A /目录/地方)

I am looking for the code that will allow me to scan a folder in my project, and store all file names with a .jpg extension in an array. This is the code I have to scan the main folder of my xcode project, however how do I store the names of files found inside, within an array?

let filemanager:NSFileManager = NSFileManager()
let files = filemanager.enumeratorAtPath(NSHomeDirectory())
while let file = files?.nextObject() {
    // store all file names with extension (jpg) in array
}

解决方案

Here's an example of how it works. This function returns an array of all the files URLs in a directory and all its subdirectories from a given path.

func files(atPath: String) -> [NSURL] {
    var urls : [NSURL] = []
    let dirUrl = NSURL(fileURLWithPath: atPath)
    if dirUrl != nil {
        let fileManager = NSFileManager.defaultManager()
        let enumerator:NSDirectoryEnumerator? = fileManager.enumeratorAtURL(dirUrl!, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)
        while let url = enumerator?.nextObject() as! NSURL? {
            if url.lastPathComponent == ".DS_Store" {
                continue
            }
            urls.append(url)
        }
    }
    return urls
}


let allFiles = files("/a/directory/somewhere")

这篇关于在阵列夫特存储的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆