I have code in objective -c that is like:
- (NSArray *)PDFInDirectory:(NSString *)directoryPath
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *dirContents = [fileManager contentsOfDirectoryAtPath:directoryPath
error:nil];
return [dirContents filteredArrayUsingPredicate:self.pdfPredicate];
}
that I want translated into swift 3 in this way:
func PDFInDirectory(directoryPath: String) -> NSArray {
let dirContents = try? FileManager.default.contentsOfDirectory(atPath: directoryPath) as NSArray
return dirContents!.filtered(using: ppdfPredicate()) as NSArray
}
but when I run it fail in the line:
let dirContents = try? FileManager.default.contentsOfDirectory(atPath: directoryPath) as NSArray
Here is all code:
import UIKit
class PdfFilePicker: UITableViewController {
// Variable
var NNOTIFICATION_NAME_SELECTED_PDF = "VSSelectedPDFFile"
var documentsDirectory = ""
var inboxDirectory = ""
var pdfPredicate: NSPredicate?
var pdfFiles: NSMutableArray = []
func ddocumentsDirectory() -> String {
if self.documentsDirectory == "" {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
self.documentsDirectory = paths.object(at: 0) as! String
}
print("Document directory call")
return documentsDirectory
}
func ppdfPredicate() -> NSPredicate {
if self.pdfPredicate == nil {
self.pdfPredicate = NSPredicate(format: "self ENDSWITH '.pdf'")
}
return pdfPredicate!
}
func ppdfFiles() -> NSMutableArray {
if self.pdfFiles == [] {
self.pdfFiles = [20]
}
return pdfFiles
}
func PDFInDirectory(directoryPath: String) -> NSArray {
// Here is the probelm.
print("My dir is \(directoryPath)")
do {
let dirContents = try? FileManager.default.contentsOfDirectory(atPath: directoryPath) as NSArray
print("my dirContents \(dirContents)")
return dirContents!.filtered(using: ppdfPredicate()) as NSArray
} catch {
print("my dirPath \(directoryPath)")
}
return []
}
func populateAllPdfsFromDocumentsAndInboxDirectory() {
self.ppdfFiles().removeAllObjects()
self.populatePDFfilesInFolder(path: self.ddocumentsDirectory())
let inboxDirectory : String = URL(fileURLWithPath: self.ddocumentsDirectory()).appendingPathComponent("Inbox").absoluteString
self.populatePDFfilesInFolder(path: inboxDirectory)
self.sortPdfFilesArray()
}
// Finished until here. // Checkif it crash probably yes
func populatePDFfilesInFolder(path: String) {
var isDir: ObjCBool = false
let fileManager = FileManager.default
let isExist = fileManager.fileExists(atPath: path, isDirectory: &isDir)
if isExist == false {
print("Read file manager successfully")
let array = self.PDFInDirectory(directoryPath: path)
print("PDF Steve")
if array.count > 0 {
for fileName: String in array as! Array {
let test : String = URL(fileURLWithPath: path).appendingPathComponent(fileName).absoluteString
self.ppdfFiles().adding(test)
}
}
}
}
// Can be crash in closure
func sortPdfFilesArray() {
if self.ppdfFiles().count > 0 {
self.ppdfFiles().sort(comparator: {( a: Any, b: Any) -> ComparisonResult in
if !(a is String) || !(b is String) {
return ((a as! String).compare(b as! String))
} else {
let aString: String? = (a as? String)
let bString: String? = (b as? String)
return (aString?.compare(bString!, options: .caseInsensitive))!
}
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("SELECT_PDF", comment: "")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.populateAllPdfsFromDocumentsAndInboxDirectory()
}
// Steve Note: Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.ppdfFiles().count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
// steve note Not sure about object
cell?.imageView?.image = UIImage(named: "Icon-PDF.png")
cell?.textLabel?.text = (self.ppdfFiles().object(at: indexPath.row) as AnyObject).lastPathComponent
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
NotificationCenter.default.post(name: Notification.Name(rawValue: NNOTIFICATION_NAME_SELECTED_PDF), object: self.ppdfFiles().object(at: indexPath.row))
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
self.deleteFile(atPath: self.ppdfFiles().object(at: indexPath.row) as! String)
self.ppdfFiles().removeObject(at: indexPath.row)
self.tableView.reloadData()
}
}
func deleteFile(atPath path: String) {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: path, isDirectory: nil) {
do {
try fileManager.removeItem(atPath: path)
} catch {
print("File Manager Remove Item at Path crash")
}
}
}
}
Any help appreciated.