how to partial download a file from google drive use objective c? - objective-c

I wanna download a big file from google drive use objective,and I use the google-api-objectivec-client-read-only lib.But when I download the big file,I see the memory boom up.
For example,the file's size is 589M,the program's memory more than 600M.So I wannna partial download the file from google drive.
My code:
-(void)getFileMetadataWithService:(NSString *)fileId
{
GTLQuery *query = [GTLQueryDrive queryForFilesGetWithFileId:fileId];
[service executeQuery:query
completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *file,
NSError *error) {
if (error == nil) {
NSLog(#"Title: %#", file.title);
NSLog(#"Description: %#", file.descriptionProperty);
NSLog(#"MIME type: %#", file.mimeType);
NSLog(#"download url:%#",file.downloadUrl);
NSLog(#"export link:%#",file.exportLinks);
[self downloadFileContentWithService:#"example"
file:file];
} else {
NSLog(#"An error occurred: %#", error);
}
}];
}
-(void)downloadFileContentWithService:(NSString *)loaclpath
file:(GTLDriveFile *)file
{
NSLog(#"download file");
if (file.downloadUrl != nil)
{
NSLog(#"begin download");
GTMHTTPFetcher *fetcher =[service.fetcherService fetcherWithURLString:file.downloadUrl];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
[data writeToFile:#"/Users/mycomputer/Desktop/a.mov" atomically:YES];
[data writeToFile:#"/Users/mycomputer/Desktop/b.mov" atomically:YES];
[data writeToFile:#"/Users/mycomputer/Desktop/c.mov" atomically:YES];
NSLog(#"download ok");
} else {
NSLog(#"An error occurred: %#", error);
}
}];
}
else
{
}
}
How to modify the method to partial download a file from google drive?

OK,I fix it up.It is so easy.
I modify the code as:
-(void)downloadFileContentWithService:(NSString *)loaclpath
file:(GTLDriveFile *)file
{
NSLog(#"download file");
if (file.downloadUrl != nil)
{
NSLog(#"begin download");
GTMHTTPFetcher *fetcher =[service.fetcherService fetcherWithURLString:file.downloadUrl];
fetcher.downloadPath = #"/Users/KarlDoenitz/Desktop/download/bisaishipin.mov";
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
if (error == nil) {
NSLog(#"download ok");
} else {
NSLog(#"An error occurred: %#", error);
}
}];
}
else
{
}
}

Related

How to fetch specific data from Firestore and update it in Objective-C

I have to fetch my user from Firestore and then I want to update my image which is string. I am stuck at one place.
Here is my code:
FIRFirestore *defaultFirestore = [FIRFirestore firestore];
FIRCollectionReference *colRef = [defaultFirestore collectionWithPath:#"users"]; // to fetch my user profile
[colRef queryWhereField:#"name" isEqualTo:currentUser.name];
[colRef getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) {
if (error != nil) {
NSLog(#"Error getting documents: %#", error);
} else {
for (FIRDocumentSnapshot *document in snapshot.documents) {
NSLog(#"%#", document.data); // my profile and after that I want to update the image
// here I want to update the user image how can I do it ??
}
}
}];
try this:
FIRFirestore *defaultFirestore = [FIRFirestore firestore];
FIRCollectionReference *colRef = [defaultFirestore collectionWithPath:#"users"];
FIRQuery *query = [colRef queryWhereField:#"name" isEqualTo:#"SIDDHANT Nigam"];
[query getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) {
if (error != nil) {
NSLog(#"Error getting documents: %#", error);
} else {
FIRDocumentSnapshot *document = snapshot.documents.firstObject;
[document.reference updateData:#{
#"imageurl": #""
}];
}
}];
}

Using RCTAsyncLocalStorage + getAllKeys

I'm trying to get the AsyncStorage on iOS native code. So this is my code
- (void)jsonFromLocalRNStrogeForKey:(NSString *)key completion:(void (^)(NSDictionary * _Nullable, NSError * _Nullable))completion {
RCTResponseSenderBlock rnCompletion = ^(NSArray *response) {
NSString *jsonAsString;
if (response.count > 1) {
NSArray *response1 = response[1];
if (response1.count > 0) {
NSArray *response2 = response1[0];
if (response2.count > 1) {
jsonAsString = response2[1];
}
}
}
#try {
NSData *jsonAsData = [jsonAsString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *json = [
NSJSONSerialization
JSONObjectWithData:jsonAsData
options:NSJSONReadingMutableContainers
error:&error
];
completion(json, error);
}
#catch (NSException *exception) {
NSLog(#"error: %#", exception.reason);
NSMutableDictionary * info = [NSMutableDictionary dictionary];
[info setValue:exception.name forKey:#"ExceptionName"];
[info setValue:exception.reason forKey:#"ExceptionReason"];
[info setValue:exception.callStackReturnAddresses forKey:#"ExceptionCallStackReturnAddresses"];
[info setValue:exception.callStackSymbols forKey:#"ExceptionCallStackSymbols"];
[info setValue:exception.userInfo forKey:#"ExceptionUserInfo"];
NSError *error = [[NSError alloc] initWithDomain:#"" code:1 userInfo:info];
completion(nil, error);
}
};
// RCTAsyncLocalStorage *storage = [RCTAsyncLocalStorage new];
RCTAsyncLocalStorage *storage = [[RCTAsyncLocalStorage alloc] init];
dispatch_async(storage.methodQueue, ^{
#try {
// [storage performSelector:#selector(multiGet:callback:) withObject:#[key] withObject:rnCompletion];
[storage performSelector:#selector(getAllKeys:callback:) withObject:rnCompletion];
}
#catch (NSException *exception) {
NSLog(#"error: %#", exception.reason);
}
});
}
When I try to get one of my keys (multiGet)
[self jsonFromLocalRNStrogeForKey:#"session" completion:^(NSDictionary* data,NSError* error) {
if (data) {
NSString * name = [data valueForKeyPath: #"token"];
if (![name isKindOfClass:[NSNull class]]) {
[self reportIncomingCallFrom:name withUUID:callInvite.uuid];
}
} else {
NSLog(#"error: JSON Parsing Error: %#",error.localizedFailureReason);
}
}];
I'm always getting null
And when I try to get all the keys (...#selector(getAllKeys:...) to see what do I have in my AsyncStorage I got the exception
#"NSInvalidArgumentException" - reason: #"-[RCTAsyncLocalStorage getAllKeys:callback:]: unrecognized selector sent to instance 0x1085512c0"
The RN have RCT_EXPORT_METHOD(getAllKeys:(RCTResponseSenderBlock)callback) in RCTAsyncLocalStorage.m; but at RCTAsyncLocalStorage.h (void)getAllKeys:(RCTResponseSenderBlock)callback it doesn't exists and even adding it doesn't work (https://github.com/facebook/react-native/blob/master/React/Modules/RCTAsyncLocalStorage.h).
"react-native": "^0.48.4",
How can I return NSJsonSerialization
Firstly,
The RN have
RCT_EXPORT_METHOD(getAllKeys:(RCTResponseSenderBlock)callback) in
RCTAsyncLocalStorage.m; but at RCTAsyncLocalStorage.h
(void)getAllKeys:(RCTResponseSenderBlock)callback it doesn't exists
In Objective-C, you can invoke a method even though it is not declared in the header file using performSelector:withObject:.
Invoking this method directly (without first checking if the target respondsToSelector:) is bad practice, as the internal method declaration may change.
Secondly, this line is incorrect:
[storage performSelector:#selector(getAllKeys:callback:) withObject:rnCompletion];
Here, you're saying getAllKeys:: takes two arguments, however the implementation declares only one.
Hence, the correct way to extract all keys is the following:
dispatch_async(storage.methodQueue, ^{
if([storage respondsToSelector:#selector(getAllKeys:)]){
[storage performSelector:#selector(getAllKeys:) withObject:[^(NSArray* response){
NSLog(#"Contents: %#",response);
} copy]];
}else{
NSLog(#"storage does not respond to selector `getAllKeys:`");
}
});

OAuthTokenRequest using STTwitterAPI fails

Using following code to get OAuth token but it always fails with error
Your credentials do not allow access to this resource
I have taken following code sample from
https://github.com/nst/STTwitter/blob/master/demo_cli/reverse_auth/main.m
Even I have allowed Read and Write access in application settings at
https://apps.twitter.com/app/XXXX/permissions
STTwitterAPI *twitter = [STTwitterAPI twitterAPIWithOAuthConsumerName:nil consumerKey:#"MY CONSUMER KEY" consumerSecret:#"MY CONSUMER SECRET"];
[twitter postReverseOAuthTokenRequest:^(NSString *authenticationHeader) {
STTwitterAPI *twitterAPIOS = [STTwitterAPI twitterAPIOSWithFirstAccount];
[twitterAPIOS verifyCredentialsWithSuccessBlock:^(NSString *username) {
[twitterAPIOS postReverseAuthAccessTokenWithAuthenticationHeader:authenticationHeader successBlock:^(NSString *oAuthToken, NSString *oAuthTokenSecret, NSString *userID, NSString *screenName) {
NSLog(#"REVERSE AUTH OK");
} errorBlock:^(NSError *error) {
NSLog(#"ERROR, %#", [error localizedDescription]);
}];
} errorBlock:^(NSError *error) {
NSLog(#"ERROR");
}];
} errorBlock:^(NSError *error) {
NSLog(#"ERROR");
}];
Any help, where I am going wrong.

How return variable in main thread like as callback?

I have the following method in Objective c:
- (BOOL) authorize {
OauthObject* oauthObj = [OauthObject sharedManager];
[[Manager sharedManagerServerRequest] authorize:(oauthObj) and:login.text withPassword:password.text completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"%#", error);
if(error == NULL && data != nil) {
self.requestSuccessfull = YES;
} else {
//NSLog(#"Error: %#", error);
// Display error
}
}];
return self.requestSuccessfull;
}
Inside this function there is method authorize that does request to server and returns data in block.
Problem is that - (BOOL) authorize returns faster return self.requestSuccessfull and it is FALSE always.
This request is asynchronous so you should use block for call back. You can change code to:
- (void)authorize:(void (^)(BOOL result))completionHanlder {
OauthObject* oauthObj = [OauthObject sharedManager];
[[Manager sharedManagerServerRequest] authorize:(oauthObj) and:login.text withPassword:password.text completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"%#", error);
if(error == NULL && data != nil) {
completionHanlder(YES);
} else {
completionHanlder(NO);
//NSLog(#"Error: %#", error);
// Display error
}
}];
}
And you can use like this:
[yourInstance authorize:^(BOOL result) {
//user result here.
}];
Hope this help!

Native Facebook/iOS6 integration: Cocoa error 3840 when trying to get profile picture

I am currently using only Social.framework (no FacebookSDK) and getting starting with requesting and getting access to basic user data. Here's all the code I have (with a few properties declared outside, as you'll notice). Everything works fine in terms of getting the right permissions, but I'm getting the following output error when asking for user's profile picture:
2013-01-27 21:28:44.324 TestApp[9230:1a703] Account saved to accountStore
2013-01-27 21:28:45.002 TestApp[9230:1d603] (null)
2013-01-27 21:28:45.003 TestApp[9230:1d603] Request error: The operation couldn’t be completed. (Cocoa error 3840.)
And here is the code:
- (IBAction)btnFbLoginPressed:(id)sender
{
ACAccountType *fbAccountType = [self.accountStore accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierFacebook];
NSArray *permissions = #[#"email"];
self.requestAccessOptions = #{ACFacebookAppIdKey:FB_API_KEY, ACFacebookPermissionsKey:permissions, ACFacebookAudienceKey:ACFacebookAudienceOnlyMe};
[self.accountStore requestAccessToAccountsWithType:fbAccountType options:self.requestAccessOptions completion:^(BOOL granted, NSError *e) {
if (granted && e == nil) {
NSArray *readPermissions = #[#"user_photos"];
NSDictionary *readAcccessOptions = #{ACFacebookAppIdKey:FB_API_KEY, ACFacebookPermissionsKey:readPermissions, ACFacebookAudienceKey:ACFacebookAudienceOnlyMe};
[self.accountStore requestAccessToAccountsWithType:fbAccountType options:readAcccessOptions completion:^(BOOL granted, NSError *e) {
if (granted && e == nil) {
NSArray *accounts = [self.accountStore accountsWithAccountType:fbAccountType];
self.facebookAccount = [accounts lastObject];
[self.accountStore saveAccount:self.facebookAccount withCompletionHandler:^(BOOL success, NSError *error) {
if (error != nil || !success) {
NSLog(#"Error saving account to accountStore: %#", error.localizedDescription);
} else {
NSLog(#"Account saved to accountStore");
}
}];
NSString *uid = [NSString stringWithFormat:#"%#", [[self.facebookAccount valueForKey:#"properties"] valueForKey:#"uid"]];
NSString *url = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture", uid];
NSURL *profilePictureURL = [NSURL URLWithString:url];
SLRequest *profilePictureRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:profilePictureURL parameters:nil];
profilePictureRequest.account = self.facebookAccount;
[profilePictureRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *e)
{
NSDictionary *responseDataDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&e];
NSLog(#"%#", responseDataDictionary);
if (e != nil) {
NSLog(#"Request error: %#", e.localizedDescription);
} else {
}
}];
} else {
NSLog(#"Read permissions request error: %#", e.localizedDescription);
}
}];
} else {
NSLog(#"Basic permissions request error: %#", e.localizedDescription);
}
}];
}
You can see that the reponseDataDictionary is null and something happens when parsing the data. I noticed a couple of other threads on SO about the same error code, but no luck so far. My guess is that either 1) there's something wrong with my Facebook code, or 2) I'm parsing the data incorrectly. Any help's appreciated!
Note: I would like to stick to using the Social/Account frameworks only.
UPDATE: Slight modification thanks to a suggestion in the comments.
Changed code:
[profilePictureRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *e)
{
NSLog(#"Request error value: %#", e.localizedDescription);
NSError *jsonError = nil;
NSDictionary *responseDataDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&jsonError];
NSLog(#"Response data dictionary value: %#", responseDataDictionary);
if (jsonError != nil) {
NSLog(#"Serialization error: %#", jsonError.localizedDescription);
} else {
NSLog(#"Serialization successful");
}
}];
Output:
2013-01-28 18:55:16.265 TestApp[9565:1ae03] Account saved to accountStore
2013-01-28 18:55:17.640 TestApp[9565:1b503] Request error value: (null)
2013-01-28 18:55:17.640 TestApp[9565:1b503] Response data dictionary value: (null)
2013-01-28 18:55:17.642 TestApp[9565:1b503] Serialization error: The operation couldn’t be completed. (Cocoa error 3840.)
The profilePictureRequest is returning an image and not JSON. Use + (CIImage *)imageWithData:(NSData *)data to convert the response to an image.