12/08/2018, 18:15

Xử lý files trong Swift

1. Chọn files trong device 1.1 Chọn file Để chọn được files trong iOS bạn có thể dùng UIDocumentPickerViewController Ví dụ: import UIKit import MobileCoreServices // Bạn cần import MobileCoreServices vì kiểu dữ liệu của files (PDF, PNG, ....) được định nghĩa ở đây class ViewController: ...

1. Chọn files trong device

1.1 Chọn file

Để chọn được files trong iOS bạn có thể dùng UIDocumentPickerViewController

Ví dụ:

import UIKit
import MobileCoreServices // Bạn cần import MobileCoreServices vì kiểu dữ liệu của files (PDF, PNG, ....) được định nghĩa ở đây

class ViewController: UIViewController {

    func showFilePicker() {
        // kUTTypePDF là lọc files PDF, bạn có thể thêm nhiều kiểu dữ liệu khác nếu cần.
        let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as NSString as String],
                                                            in: .import)
        documentPicker.delegate = self
        documentPicker.modalPresentationStyle = .formSheet
        if #available(iOS 11.0, *) {
            documentPicker.allowsMultipleSelection = false
        }
        self.present(documentPicker, animated: true, completion: nil)
    }

}

extension ViewController: UIDocumentPickerDelegate {

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        print(url)
    }

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        print(urls)
    }

    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    }

}

1.2 Lấy kích thước của file

let size = sizeForLocalFilePath(filePath: url.path)

func sizeForLocalFilePath(filePath: String) -> UInt64 {
    do {
        let fileAttributes = try FileManager.default.attributesOfItem(atPath: filePath)
        if let fileSize = fileAttributes[FileAttributeKey.size]  {
            return (fileSize as! NSNumber).uint64Value
        } else {
            print("Failed to get a size attribute from path: (filePath)")
        }
    } catch {
        print("Failed to get file attributes for local path: (filePath) with error: (error)")
    }
    return 0
}

2. Mở file

Để mở 1 file bạn có thể dùng UIDocumentInteractionController. Bạn cần truyền vào file đã được download về device nhé, chứ files URL trỏ đến server thì không mở được đâu             </div>
            
            <div class=

0