我们如何在Google Drive API上上传多个文档文件

时间:2018-10-08 11:52:54

标签: ios swift google-drive-api

我想上传多个文档文件(例如PDF,文本等),我可以上传单个文件到驱动器。以下是我将单个文件上传到驱动器的代码。我已经使用了Document Picker Controller。

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


    if let documentsDir = url as URL? {

        print("import result : \(documentsDir)")

        let indexFileName = (documentsDir.pathComponents.last)!
        print("THE FILE NAME", indexFileName)

        let testFilePath = documentsDir.appendingPathComponent("").path

        drive?.uploadFile("FolderNameOnDrive", filePath: testFilePath, MIMEType: "image/pdf") { (fileID, error) in
            print("Upload file ID: \(String(describing: fileID)); Error: \(String(describing: error?.localizedDescription))")

            print("THE FILE ID IS",fileID ?? "")
            print("The test File Path", testFilePath)
        }
    }

}

testFilePath是来自文档目录的文档路径,使用户可以选择文件。

我已启用documentPicker.allowsMultipleSelection = true。但仍然停留在多次上传中。

2 个答案:

答案 0 :(得分:0)

您可以只上传一个,然后使用DispatchGroup完成所有文件上传后的完成:

struct File {
        let name: String
        let path: URL
        let MIMEType: String
    }

let uploadGroup = DispatchGroup()
var drives = [Drive]()

func upload(files: [File], completion: () -> Void){
    let drive = Drive()
    drives.append(drive)
    for file in files {
        uploadGroup.enter()
        drive.uploadFile(file.name, filePath: file.path, MIMEType: file.MIMEType) { (fileID, error) in
            guard error == nil else {
                print("error: \(error)")
                uploadGroup.leave()
            }

            print("uploaded: \(fileID)")
            uploadGroup.leave()
        }
    }

        uploadGroup.notify(queue: DispatchQueue.main) {
            completion()
        }
}

P.S。但是您需要重新制作您的上载程序类以进行多次上载,或者为每个上载创建新实例,就像我的示例一样

答案 1 :(得分:0)

覆盖didPickDocumentsAt而不是didPickDocumentAt。注意复数。