How to download google files in google drive sdk? - objective-c

In this way, I download a image successfully:
GTLServiceDrive *drive = ...;
GTLDriveFile *file = ...;
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#?alt=media",file.identifier];
GTMSessionFetcher *fetcher = [drive.fetcherService fetcherWithURLString:url];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
NSLog(#"Retrieved file content");
// Do something with data
} else {
NSLog(#"An error occurred: %#", error);
}
}];
the document of google drive sdk tell me to download a pdf or google docs should use another url:
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/drive/v3/files/%#/export?alt=media&mimeType=application/pdf",file.identifier];
but I failed, error is this:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "badRequest",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}

In downloading file make sure your app must be authorized with a scope that allows reading of file content. For example, an app using the drive.readonly.metadata scope would not be authorized to download the file contents. Users with edit permission may restrict downloading by read-only users by setting the viewersCanCopyContent field to true.
There is another way to download a file by using the partial download. It involves downloading only a specified portion of a file. You can specify the portion of the file you want to dowload by using a byte range with the Range header.
This SO question is using partial download. I think it can help you.
This code demonstrate how to download a Google Document in PDF format.
String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().export(fileId, "application/pdf")
.executeMediaAndDownloadTo(outputStream);

Related

don't have permission to save the file

Recently i'm using cocos 2d-x ver-3.17.
I complied resource to jsc then make a server to upload it like update-server, control version i think.
Now when i build the app in IOS which will connect to update-server then download the file jsc. Unfortunately, when the app trying to save the file down it falling to the error " don't have permission to save the file". What should i do to provide them permission to solve it.
Fail to create directory :
"/var/mobile/Containers/Data/Application/C9BA91B9-AEF6-4FF8-B5F3-061AF15441A5/Documents_temp/":
You don’t have permission to save the file “Documents_temp” in the
folder “C9BA91B9-AEF6-4FF8-B5F3-061AF15441A5”.
bool FileUtilsApple::createDirectory(const std::string& path)
{
CCASSERT(!path.empty(), "Invalid path");
if (isDirectoryExist(path))
return true;
NSError* error;
bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.c_str()] withIntermediateDirectories:YES attributes:nil error:&error];
if(!result && error != nil)
{
CCLOGERROR("Fail to create directory \"%s\": %s", path.c_str(), [error.localizedDescription UTF8String]);
}
return result;
}
How can i get permission to save the files ?
solved : https://forum.cocos.com/t/topic/47298/3
Self-reliance, find out the problem, you need to define the file directory
find your initAssetManager :
var storagePath = (jsb.fileUtils ? jsb.fileUtils.getWritablePath() : "./")+"temp/";

Get Method is not working inside App if URL contains .info?

I am making a simple GET Method inside the APP , But its Not Working on some URL..
For Eg :
https://lievensberg.webcamconsult.com/wachtkamer/ZwXIk9KcYvMBFeJWiSeUQQ.json . - this is working (contains .com)
https://soa-webcamconsult.sense.info/wachtkamer/pk3rs51FpFUQkrHOJ0uBHg.json - this is not working (contains .info)
Both URL is Working Perfect in Browser...!
I am using AFNetworking, Any one can Help Me Please ?
This is the Call Method , Url given below
//https://soa-webcamconsult.sense.info/wachtkamer/pk3rs51FpFUQkrHOJ0uBHg.json
NSDictionary *header = [NSDictionary dictionaryWithObjectsAndKeys:#"application/json",#"Content-Type", #"application/json", #"Accept", #"iPhone",#"User-Agent",nil];
NSLog(#"url---%#",url);
NSLog(#"header---%#",[Utilities printJson:header]);
[SSNetworkClient initServerCallWithURL:url requestMethod:SSRequestMethodGET requestSerialize:YES headers:header imageData:nil imageDataName:nil parameters:nil success:^(id object) {
completionBlock(YES,object);
} failure:^(id object) {
failureCompletion(NO,object);
}];
In you response of second url you are getting invalid json and which should be like this,
{
"status": {
"code": "on_time",
"message": "U bent op tijd",
"content": "Uw afspraak begint om *|afspraak_tijd|* ."
},
"slave": {
"name1": "Dhr. sunny",
"name2": "Meneer sunny"
},
"master": {
"name1": "Mr beheerder"
},
"push": {
"origin": "pubsub.pubnub.com",
"pub_key": "pub-c-a6ca4c51-0a6f-475d-8f93-f53f48ba117b",
"sub_key": "sub-c-97578f62-3587-11e3-be49-02ee2ddab7fe",
"uuid": "sunny-5a323ac22cacff0004c2a717",
"channels": ["5a29524f2b4faa000470384a", "5a323ac22cacff0004c2a717"]
},
"lobby_message": "",
"contact_info": "/dyncontent/pk3rs51FpFUQkrHOJ0uBHg"
}
Above is the correct json which you will need to improve in your api response
And if you wont verify just create the json file with above json it will work perfectly with browser and with your .info api response json it won't work so you need to improvise your .info json file response
My Mozilla browser Quantum version response,

NSUrlSessionTaskDelegate server response

I'm using NSUrlSessionTaskDelegate to upload files into a server, but server codes aren't given back in the didCompleteWithError. This matches the apple documentation:
Server errors are not reported through the error parameter. The only
errors your delegate receives through the error parameter are
client-side errors, such as being unable to resolve the hostname or
connect to the host.
But is there any other way I can get the server error's like a 400 Bad Request or something? Because every file upload is a success now even when I get a bad request back..
Something like this should work. But I didn't test it. It is posted as an answer just because of easier code formatting...
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
if (!error)
{
NSHTTPURLResponse *response = task.response;
NSLog(#"StatusCode: %d",response.statusCode);
if (response.statusCode != 200) //note that other 2xx codes might be valid
{
//....
}
}
else
{
NSLog(#"Error: %#",error.description);
}
}
In SWIFT 5, you can do the same like below.
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print(task.response ?? "")
if let urlResponse = task.response as? HTTPURLResponse {
print(urlResponse.statusCode)
}
}

How to get all mime types Google Drive Api IOS

I am trying to integrate Google Drive Api for IOS. I am testing their example program here
a.k.a DrEdit when they upload or download a file they use mimetype such as when they upload a file
[GTLUploadParameters uploadParametersWithData:fileContent MIMEType:#"text/plain"];
when api downloads the same file it uses
GTLQueryDrive *query = [GTLQueryDrive queryForFilesList];
query.q = #"mimeType = 'text/plain'";
JSON values for a file
{
"kind": "drive#file",
"id": string,
"etag": etag,
"selfLink": string,
"title": "file_name",
"mimeType": "mime/type",
"description": "Stuff about the file"
...
"downloadUrl": string,
...
}
Now I wonder how can I download all the files in users folder that has different file extensions such as pdf,doc etc...
How can I display/list all the documents in users google drive account?
Two things:
1) The empty query seems to return all files:
query.q = #"";
2) Make sure you request access to all files in the auth (initWithScope:kGTLAuthScopeDrive). The DrEdit example defaults to only accessing files created by the app.
GTMOAuth2ViewControllerTouch *authViewController =
[[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDrive // Auth to all files and docs
clientID:kClientId
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:finishedSelector];
Mime types
I have found this mime types which are supported by google drive. U can use them in download or upload.

iOS DropboxSDK, get remote subdirectories and contents

I have a remote directory with several subdirectories and files in them on Dropbox.
remote side:
-Mobile Profiles *(root)*
-- Custom Profiles
--- Profile1
--- Profile2
--- Profile3
Uploading the files and directories / and subdirectories with files is not a problem. I am having a brain fart when it comes to getting the subdirectories and their contents from dropbox to the device.
put
-(void)backupCustomProfiles {
for ( NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:MP_CUSTOM error:&error] ) {
[self.restClient uploadFile:file toPath:#"/Mobile Profiles/Custom Profiles/" fromPath:EasyStrings(MP_CUSTOM,file)];
}
}
get
-(void)restoreCustomProfiles {
for ( ) {
/* ? */
}
}
I am not sure how to iterate through the subdirectories on the remote side.
First load the directory metadata, then load the files that it references.
To limit the number of parallel fetches, use a NSOperationQueue for all of the loadMetadata and loadFile calls to limit the number of parallel fetches. And to avoid redundant file downloads, remember the downloaded metadata in a plist.
- (void) restoreCustomProfiles
{
[self.client loadMetadata:#"/Mobile Profiles/Custom Profiles" withHash:hash];
}
- (void) restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata
{
for (DBMetadata* child in metadata.contents) {
NSString *path = [child.path lowercaseString];
if (child.isDirectory) {
[client loadMetadata:child.path withHash:hash];
} else {
[client loadFile:pathToDownload intoPath:[
self.directory stringByAppendingString:path]];
}
}
}
- (void) restClient:(DBRestClient*)client loadedFile:(NSString*)destPath
{
// successfully downloaded a file to destPath
}