如何使用swift在谷歌驱动器中创建文件夹和文件

时间:2017-08-09 09:12:02

标签: ios swift

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

我正在使用swift并使用此代码

<!DOCTYPE html>
<html>

<head>
  <title>Assignment 1</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
  <div class="container">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Name</th>
          <th>Physics</th>
          <th>Maths</th>
          <th>Chemistry</th>
          <th>Lowest Marks</th>
          <th>Highest Marks</th>
        </tr>
      </thead>
      <tbody>
<?php 
$marks = array( 
            "mohammad" => array(
                                "physics" => 35,        
                                "maths" => 30,      
                                "chemistry" => 39       
                            ),
            "qadir" => array(
                                "physics" => 30,
                                "maths" => 32,
                                "chemistry" => 29
                            ),
            "zara" => array(
                                "physics" => 31,
                                "maths" => 22,
                                "chemistry" => 39
                            )
            );                   
$average=0;
$lowest=0;
$greatest=0;
$physics=0;
$chemistry=0;
$maths=0;
$arr=Array(0);
$count=0;
foreach($marks as $row => $innerArray){
    $average=0;
    $lowest=0;
    $greatest=0;
    $count=0;
    echo "<tr>";
    echo "<td>$row</td>";
    foreach($innerArray as $innerRow => $value){                                
        if($value>$greatest){
            $greatest=$value;
        }else{
            $lowest=$value;
        }
        echo "<td>$value</td>"; 
        $arr[$count]+=$value;
        $count++;                               
    }   
    $average=round($average/3,2);                           
    echo "<td>$lowest</td>";
    echo "<td>$greatest</td>";
    echo "</tr>";
}
echo "<tr><td>Average Marks</td><td>".round($arr[0]/3,2)."</td><td>".round($arr[1]/3,2)."</td><td>".round($arr[2]/3,2)."</td></tr>";
?>
      </tbody>
    </table>
  </div>
</body>

</html>

但无法创建文件夹。谁能帮我吗。提前谢谢。

3 个答案:

答案 0 :(得分:1)

    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"))")

}

所需图书馆的链接: - Download libraries

在项目中包含CkoAuthGoogle,CkoRest和CkoJsonObject标头文件。

答案 1 :(得分:0)

这基本上是由于范围,我必须在范围区域给出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)")
        }
    })
}

答案 2 :(得分:0)

快速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文档中的分段文件上传here