如何从文档目录中选择所有类型的数据或文档文件以及如何在集合视图中呈现它

问题描述 投票:0回答:1

我需要从文档目录中获取所有类型的数据,并且我想在集合视图单元格内呈现数据...我想在选择单元格时读取或打开数据...如果您有任何解决方案,请与我分享...

我希望...这个问题会得到解决,因为我尝试了很多次但没有成功

directory fetch document
1个回答
0
投票

当然!这是带有更正缩进的完整代码:

import UIKit
import AVKit
import PDFKit
import QuickLook

class FileCollectionViewController: UICollectionViewController, QLPreviewControllerDataSource {

    var files: [URL] = [] // Array to store file URLs in the document directory

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchFilesFromDocumentDirectory()
    }

    func fetchFilesFromDocumentDirectory() {
        // Replace "DocumentDirectory" with your actual directory name if different
        if let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            do {
                // Get all files in the document directory
                let fileURLs = try FileManager.default.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil, options: [])

                // Filter files based on your criteria (e.g., file extensions)
                files = fileURLs.filter {
                    $0.pathExtension.lowercased().contains("pdf") ||
                    $0.pathExtension.lowercased().contains("jpg") ||
                    $0.pathExtension.lowercased().contains("txt") ||
                    $0.pathExtension.lowercased().contains("mp4")
                }

                // Reload the collection view to display the fetched files
                collectionView.reloadData()
            } catch {
                print("Error while fetching files: \(error.localizedDescription)")
            }
        }
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return files.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FileCell", for: indexPath) as! FileCollectionViewCell

        let fileURL = files[indexPath.item]

        // Configure the cell based on the file type
        switch fileURL.pathExtension.lowercased() {
        case "jpg", "jpeg", "png":
            // Display image
            cell.imageView.image = UIImage(contentsOfFile: fileURL.path)
            cell.titleLabel.text = "Image"
        case "pdf":
            // Display PDF document
            cell.pdfView.displayMode = .singlePage
            cell.pdfView.displayDirection = .vertical
            if let pdfDocument = PDFDocument(url: fileURL) {
                cell.pdfView.document = pdfDocument
            }
            cell.titleLabel.text = "PDF"
        case "txt":
            // Handle text file
            cell.titleLabel.text = "Text"
        case "mp4":
            // Handle video file
            let player = AVPlayer(url: fileURL)
            let playerLayer = AVPlayerLayer(player: player)
            playerLayer.frame = cell.contentView.bounds
            cell.contentView.layer.addSublayer(playerLayer)
            cell.titleLabel.text = "Video"
        default:
            cell.titleLabel.text = "Unknown"
        }

        return cell
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let selectedFileURL = files[indexPath.item]

        // Perform actions based on the selected file
        switch selectedFileURL.pathExtension.lowercased() {
        case "jpg", "jpeg", "png":
            // Handle image file selection
            openImageFile(selectedFileURL)
        case "pdf":
            // Handle PDF file selection
            openPDFFile(selectedFileURL)
        case "txt":
            // Handle text file selection
            openTextFile(selectedFileURL)
        case "mp4":
            // Handle video file selection
            openVideoFile(selectedFileURL)
        default:
            // Handle other file types if needed
            print("Selected File: \(selectedFileURL.lastPathComponent)")
        }
    }

    // MARK: - File Handlers

    func openImageFile(_ fileURL: URL) {
        // Handle image file selection
        // You can display the image in a new view controller or use a third-party image viewer
    }

    func openPDFFile(_ fileURL: URL) {
        // Handle PDF file selection
        let pdfViewController = QLPreviewController()
        pdfViewController.dataSource = self
        present(pdfViewController, animated: true, completion: nil)
    }

    func openTextFile(_ fileURL: URL) {
        // Handle text file selection
        let textContent = try? String(contentsOf: fileURL, encoding: .utf8)
        // Display the text content in a new view controller or another appropriate view
        print("Text Content: \(textContent ?? "")")
    }

    func openVideoFile(_ fileURL: URL) {
        // Handle video file selection
        let playerViewController = AVPlayerViewController()
        playerViewController.player = AVPlayer(url: fileURL)
        present(playerViewController, animated: true) {
            playerViewController.player?.play()
        }
    }

    // MARK: - QLPreviewControllerDataSource

    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }

    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
        return files.first! as QLPreviewItem
    }
}

class FileCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var pdfView: PDFView!
    @IBOutlet weak var titleLabel: UILabel!
}

请注意,如果“DocumentDirectory”占位符与您的实际目录名称不同,则应将其调整为不同的名称。另外,请确保您的故事板或 XIB 文件具有带有重用标识符“FileCell”的集合视图单元以及图像视图、PDF 视图和标题标签的必要出口。

© www.soinside.com 2019 - 2024. All rights reserved.