5

I can't figure out how to download a Google Drive file in Swift. I followed the modified quickstart from Google Objective-C API 'GTL' with Swift and that worked. I can't translate the objective C code from the google drive API on downloading files. I've searched around and can't find anything. How can I get this to work?

Community
  • 1
  • 1
user3142972
  • 897
  • 1
  • 8
  • 11

3 Answers3

4

You can use this function for downloading files with the Google Drive API in Swift:

func downloadFile(file: GTLDriveFile){
    let url = "https://www.googleapis.com/drive/v3/files/\(file.identifier!)?alt=media"

    let fetcher = drive.fetcherService.fetcherWithURLString(url)

    fetcher.beginFetchWithDelegate(
        self,
        didFinishSelector: #selector(ViewController.finishedFileDownload(_:finishedWithData:error:)))
}

(In this case drive is the GTLServiceDrive - the same as in the Documentation)

Then you need to implement the function finishedFileDownload that will be called once the download is completed:

func finishedFileDownload(fetcher: GTMSessionFetcher, finishedWithData data: NSData, error: NSError?){
    if let error = error {
        //show an alert with the error message or something similar
        return
    }

    //do something with data (save it...)
}
Keiwan
  • 8,031
  • 5
  • 36
  • 49
1

Actual for Swift 5.

func download(file: GTLRDrive_File) {
    let url = "https://www.googleapis.com/drive/v3/files/\(file.identifier!)?alt=media"
    let fetcher = drive.fetcherService.fetcher(withURLString: url)
    fetcher.beginFetch(completionHandler: { data, error in
        if let error = error {
            print(error.localizedDescription)
        }

        //Do something with data
    })
}
0

Swift 5 with progress block. file.size returns nil for some reason so I used fetcher.response?.expectedContentLength instead.

func download(file: GTLRDrive_File, service: GTLRDriveService) {
        
    let url = "https://www.googleapis.com/drive/v3/files/\(file.identifier)?alt=media"
    let fetcher = service.fetcherService.fetcher(withURLString: url)
    fetcher.beginFetch(completionHandler: { fileData, error in
        
        if error == nil {
            
            print("finished downloading Data...")
            print(fileData as Any)
            
        
        } else {
            
            print("Error: \(String(describing: error?.localizedDescription))")
        }
    })
    
    fetcher.receivedProgressBlock = { _, totalBytesReceived in
        
        if let fileSize = fetcher.response?.expectedContentLength {
            
            let progress: Double = Double(totalBytesReceived) / Double(fileSize)
            
            // update progress bar here
            print(progress)
        }
    }
}
Timchang Wuyep
  • 629
  • 7
  • 10