无法使用Swift中的Google Drive Api将图像上传到Google云端硬盘

时间:2016-06-01 07:23:16

标签: ios swift2 google-drive-api

我正在尝试使用Swift中的Google Drive Api将图像上传到Google云端硬盘。但是收到以下错误消息: - 意外回复数据(上传到错误的网址?) {“error”:{“code”:401,“message”:“需要登录”,“数据”:[{“domain”:“global”,“reason”:“required”,“message”:“需要登录” ”, “的locationType”: “首部”, “位置”: “授权”}]}, “ID”: “gtl_3”}

她是我的代码 -

      func uploadFileToDrive() {
        print("uploading Photo")
        let dateFormat  = NSDateFormatter()
        dateFormat.dateFormat = "'Quickstart Uploaded File ('EEEE MMMM d, YYYY h:mm a, zzz')"

        let file = GTLDriveFile()
        file.name = dateFormat.stringFromDate(NSDate())
        file.descriptionProperty = "Uploaded from Google Drive IOS"
        file.mimeType = "image/png"

        let fileManager = NSFileManager.defaultManager()
        let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

        // If array of path is empty the document folder not found
        guard urls.count == 0 else {
            let imageURL = urls.first!.URLByAppendingPathComponent("image.png")
            // Data object to fetch image data
            do {
                let imageData = try NSData(contentsOfURL: imageURL, options: NSDataReadingOptions())
                let uploadParameters = GTLUploadParameters(data: imageData, MIMEType: file.mimeType)
                let query = GTLQueryDrive.queryForFilesCreateWithObject(file, uploadParameters: uploadParameters) as GTLQueryDrive
                self.driveService.executeQuery(query, completionHandler:  { (ticket, insertedFile , error) -> Void in
                    let myFile = insertedFile as? GTLDriveFile

                    if error == nil {
                        print("File ID \(myFile?.identifier)")
                    } else {
                        print("An Error Occurred! \(error)")
                    }

                })
            } catch {
                print(error)
            }

            return
        }
    }

请帮助我,我做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要身份验证才能上传到Google云端硬盘。使用Drive API with iOS的身份验证过程是:

  1. 在GDC中为您的应用创建oAuthclientID。
  2. 设置范围。

    NSString范围= @"https://www.googleapis.com/auth/drive.file"
    NSString * keychainItemName = @“我的应用程序”;
    NSString * clientId = @“PUT_CLIENT_ID_HERE”;

  3. 检查存储的凭据。

  4. 必要时请求授权。
  5. 处理身份验证响应。
  6. 身份验证和授权完成后,您现在可以Upload in Google Drive