Ios 如何使用swift在google drive中创建文件夹和文件

Ios 如何使用swift在google drive中创建文件夹和文件,ios,swift,Ios,Swift,我正在使用google drive SDK创建文件夹,但无法创建。我可以登录并获取所有文件和文件夹,但无法创建它 我使用的是swift并使用了此代码 let metaData = GTLRDrive_File() metaData.name = "xyz" metaData.mimeType = "application/vnd.google-apps.folder" let querys = GTLRDriveQuery_FilesCreate.query(withOb

我正在使用google drive SDK创建文件夹,但无法创建。我可以登录并获取所有文件和文件夹,但无法创建它

我使用的是swift并使用了此代码

let metaData = GTLRDrive_File()
    metaData.name = "xyz"
    metaData.mimeType = "application/vnd.google-apps.folder"
    let querys = GTLRDriveQuery_FilesCreate.query(withObject: metaData, uploadParameters: nil)

    querys.fields = "id"

    //service.executeQuery(querys, delegate: self, didFinish: nil)

    self.service.executeQuery(querys) { (ticket:GTLRServiceTicket, object:Any?, error:Error?) in
        // Put your completion code here
    }
但无法创建文件夹。有人能帮我吗。提前谢谢

    func chilkatTest() {
        var success: Bool = true

    //  It requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    //  This example uses a previously obtained access token having permission for the
    //  Google Drive scope.

    let gAuth = CkoAuthGoogle()
    gAuth.AccessToken = "GOOGLE-DRIVE-ACCESS-TOKEN"

    let rest = CkoRest()

    //  Connect using TLS.
    var bAutoReconnect: Bool = true
    success = rest.Connect("www.googleapis.com", port: 443, tls: true, autoReconnect: bAutoReconnect)

    //  Provide the authentication credentials (i.e. the access token)
    rest.SetAuthGoogle(gAuth)

    //  -------------------------------------------------------------------------
    //  A multipart upload to Google Drive needs a multipart/related Content-Type
    rest.AddHeader("Content-Type", value: "multipart/related")

    //  Specify each part of the request.

    //  The 1st part is JSON with information about the file.
    rest.PartSelector = "1"
    rest.AddHeader("Content-Type", value: "application/json; charset=UTF-8")

    let json = CkoJsonObject()
    json.AppendString("name", value: "testHello.txt")
    json.AppendString("description", value: "A simple file that says Hello World.")
    json.AppendString("mimeType", value: "text/plain")

    //  To place the file in a folder, we must add a parents[] array to the JSON
    //  and list the folder id's.  It's possible for a file to be in multiple folders at once
    //  if it has more than one parent.  If no parents are specified, then the file is created
    //  in the My Drive folder.
    //  Note: We'll assume we already have the id if the folder.  It is the id's that are specified here,
    //  not the folder names.
    var parents: CkoJsonArray? = json.AppendArray("parents")
    var folderId: String? = "0B53Q6OSTWYolY2tPU1BnYW02T2c"
    parents!.AddStringAt(-1, value: folderId)
    parents = nil

    rest.SetMultipartBodyString(json.Emit())

    //  The 2nd part is the file content, which will contain "Hello World!"
    rest.PartSelector = "2"
    rest.AddHeader("Content-Type", value: "text/plain")

    var fileContents: String? = "Hello World!"
    rest.SetMultipartBodyString(fileContents)

    var jsonResponse: String? = rest.FullRequestMultipart("POST", uriPath: "/upload/drive/v3/files?uploadType=multipart")
    if rest.LastMethodSuccess != true {
        print("\(rest.LastErrorText)")
        return
    }

    //  A successful response will have a status code equal to 200.
    if rest.ResponseStatusCode.integerValue != 200 {
        print("response status code = \(rest.ResponseStatusCode.integerValue)")
        print("response status text = \(rest.ResponseStatusText)")
        print("response header: \(rest.ResponseHeader)")
        print("response JSON: \(jsonResponse!)")
        return
    }

    //  Show the JSON response.
    json.Load(jsonResponse)

    //  Show the full JSON response.
    json.EmitCompact = false
    print("\(json.Emit())")

    //  A successful response looks like this:
    //  {
//   "kind": "drive#file",
    //    "id": "0B53Q6OSTWYoldmJ0Z3ZqT2x5MFk",
    //    "name": "Untitled",
    //    "mimeType": "text/plain"
    //  }

    //  Get the fileId:
    print("fileId: \(json.StringOf("id"))")

}
所需库的链接:-


在您的项目中包括CkoAuthGoogle、CkoRest和CkoJsonObject头文件。

这基本上是由于范围的原因,我必须在范围区域中提供kGTLRAuthScopeDriveFile

private let scopes = [kGTLRAuthScopeDriveReadonly,kGTLRAuthScopeDriveFile]
在谷歌里也一样

func folder(){

    let metadata = GTLRDrive_File()
    metadata.name = "eBilling"

    metadata.mimeType = "application/vnd.google-apps.folder"
    let querys = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: nil)
    querys.fields = "id"

    self.service.executeQuery(querys, completionHandler: {(ticket:GTLRServiceTicket, object:Any?, error:Error?) in

        if error == nil {

            self.listFiles()

        }
        else {
            print("An error occurred: \(error)")
        }
    })
}

Swift 5

如果您希望只创建一个文件夹而不上载文件, 我能够像这样使用Google的REST端点创建一个驱动器文件夹

此函数使用auth令牌、文件名和参数创建一个URLRequest,然后可以在URLSession中发送该URLRequest

func createFolderRequest(authToken: String, folderName: String) -> URLRequest {

    let headers = [
      "Content-Type": "multipart/related; boundary=123456789",
      "Authorization": "Bearer " + authToken
    ]

    let body =
    """
    --123456789
    Content-Type: application/json

    {
      "name": "\(folderName)",
      "mimeType": "application/vnd.google-apps.folder"
    }

    --123456789--
    """
    var request = URLRequest(url: URL(string: "https://www.googleapis.com/upload/drive/v3/files")!)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = body.data(using: .utf8)
    request.addValue(String(body.lengthOfBytes(using: .utf8)), forHTTPHeaderField: "Content-Length")

    return request
}

我参考了用于多部分文件上传的google文档

感谢回复什么是CkoAuthGoogle,以及如何访问accessTokenCkoAuthGoogle-提供使用服务帐户和访问令牌(google API请求中使用的访问令牌)验证对google云平台API和google Apps API的调用的功能。此属性是在成功调用OccessAccessToken时设置的。我希望这个解决方案对你有帮助!已为库添加了链接。您可以从include文件夹在项目中包含3个主要头文件:-CkoAuthGoogle、CkoRest和CkoJsonObject@Udaikumar我的解决方案对你有帮助吗?你对答案满意吗?检查此链接并下载适当的库。以下几点对我的项目有效。