I'm using the Google APIs Client Library for Objective-C (GTL) to access the Google Drive API.
According to it's Introduction to the Google APIs Client Library for Objective-C,
Query execution by the service is inherently asynchronous.
Which means when you try to create a path like: root/a/b/c
, before you can create folder b
, you'll have to:
Make sure a
is created, if not, create it before b
was trying to check it's parentRef
.
Know the id
of folder a
so you can create b
in it.
And same goes to c
.
I use something like the following to get the id
of a folder by name within a known parent folder id:
// Get parentID by name "parent".
let query = GTLQueryDrive.queryForChildrenListWithFolderId(parentID)
query.q = "mimeType='application/vnd.google-apps.folder' and '\(parentID)' in parents and trashed=false and title='\(name)'"
query.maxResults = 1
GTLFileTicket = GTLDriveService.executeQuery(
query,
completionHandler: {(
ticket: GTLServiceTicket!,
object: AnyObject!,
error: NSError!) -> Void in
// Callback
self.GTLFileTicket = nil
if error == nil {
// Get the id from the object. If nil make another query to create a folder named "name" within folder "parentID".
} else {
// error handles here.
}
})
In the other part of the project, I called the above method within a for loop:
var parent = "root"
for item in array {
createFolderIfNotExisted(item, parent: parent)
parent = item
}
Apparently, it will fail and end up creating only the first folder as the 2nd query starts before the 1st query even finished. I googled around but didn't see a way to make it synchronous calls instead. (Tho I saw Java API branch can have something like .await()
?)
Is there a way to make sure the calls can be executed in sequence?
Avoid using a synchronous for loop. The createFolder function should call back when it's complete; that callback should start the next loop iteration.