取得路径下的paths
,判断是文件还是文件夹
查看Bundle
下Doc
目录下的文件
class ViewController: UIViewController {
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
let basePath = Bundle.main.bundlePath+"/Doc"
let vc = ListTVC()
vc.fullPath = basePath
navigationController?.pushViewController(vc, animated: true)
}
FileModel.swift
import Foundation
struct FileModel {
///完整路径
var path = ""
///是否文件夹
var isDirectory = false
init(_ path: String, isDirectory: Bool) {
self.path = path
self.isDirectory = isDirectory
}
}
FileMgr.swift
let fileMgr = FileManager.default
/**
let fm = FileMgr()
fm.getSubWithPath(Bundle.main.bundlePath+"/Doc")
*/
class FileMgr {
}
extension FileMgr {
func getSubWithPath(_ fullPath: String) -> [FileModel] {
var result: [FileModel] = []
if let contents = try? fileMgr.contentsOfDirectory(atPath: fullPath) {
DebugLog(contents)
for content in contents {
var isDir = ObjCBool(false)
let path = fullPath.appending("/")+content
DebugLog(path)
if fileMgr.fileExists(atPath: path, isDirectory: &isDir) {
//DebugLog(isDir.boolValue, path)
result.append(FileModel(path, isDirectory: isDir.boolValue))
}
}
}
return result
}
}
展示文件/夹列表ListTVC.swift
import UIKit
class ListTVC: UITableViewController {
var fullPath = ""
var dataList: [FileModel] = []
let fileMgr = FileMgr()
override func viewDidLoad() {
super.viewDidLoad()
initView()
initData()
}
fileprivate func initView() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
fileprivate func initData() {
dataList = fileMgr.getSubWithPath(fullPath)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let model = dataList[indexPath.row]
let text = (model.path as NSString).lastPathComponent
cell.textLabel?.text = (model.isDirectory ? "" : "")+text
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = dataList[indexPath.row]
if model.isDirectory {
let vc = ListTVC()
vc.navigationItem.title = (model.path as NSString).lastPathComponent
vc.fullPath = model.path
navigationController?.pushViewController(vc, animated: true)
} else {
}
}
}