Integrate iCloud into ios App and Retrieve files from iCloud - ios

I integrated iCloud into iOS app using raywenderlich https://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1
But iam unable to show all the files from iCloud to our iOS app and also need specific type of files like pdf, doc and docx
Can any one suggest me.

Follow below steps to integrate iCloud in iOS app and retrieve files.
1. Enable iCloud from your developer account.
2. Create iCloud containers entitlement at developer account.
3. Then just use below code where you want to integrate your iCloud integration.
First of all import #import and add iCloudDelegate delegate then set delegate:
// Setup iCloud
[[iCloud sharedCloud] setDelegate:self];
[[iCloud sharedCloud] setVerboseLogging:YES];
[[iCloud sharedCloud] setupiCloudDocumentSyncWithUbiquityContainer:nil];
[self showiCloudFiles];
then implementation of method showiCloudFiles below
-(void) showiCloudFiles{
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
else if ([[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == NO) {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"iCloud Disabled", #"You have disabled iCloud for this app. Would you like to turn it on again?");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
UIAlertAction* deleteButton = [UIAlertAction actionWithTitle:#"Turn On iCloud"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"userCloudPref"];
[[NSUserDefaults standardUserDefaults] synchronize];
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
}];
[alert addAction:deleteButton];
[self presentViewController:alert animated:YES completion:nil];
} else {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"Setup iCloud", #"iCloud is not available. Sign into an iCloud account on this device and check that this app has valid entitlements.");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
}];
[self presentViewController:alert animated:YES completion:nil];
}
}
After that for downloading file use UIDocumentPickerDelegate method:
#pragma mark - UIDocumentPickerDelegate
-(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
if (controller.documentPickerMode == UIDocumentPickerModeImport) {
//NSLog(#"%#",url);
[url startAccessingSecurityScopedResource];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent]; NSString *fileExtension = [newURL pathExtension]; if([fileExtension isEqualToString:#"zip"]) {if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"pages"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"numbers"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"key"] ) {
// Remove .zip if it is an iWork file
fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
}
NSError *fileConversionError;fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
// Do further code using fileData
}
}];
[url stopAccessingSecurityScopedResource];
}
}
For UIDocumentPicker visit this link iOS-8-UIDocumentPicker

Follow this guide
https://www.raywenderlich.com/12779/icloud-and-uidocument-beyond-the-basics-part-1
Download sample code at
https://github.com/rwenderlich/PhotoKeeper
Check if iCloud available
- (void)initializeiCloudAccessWithCompletion:(void (^)(BOOL available)) completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_iCloudRoot = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (_iCloudRoot != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud available at: %#", _iCloudRoot);
completion(TRUE);
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud not available");
completion(FALSE);
});
}
});
}
Query type of flies like pdf, doc and docx
- (NSMetadataQuery *)documentQuery {
NSMetadataQuery * query = [[NSMetadataQuery alloc] init];
if (query) {
// Search documents subdir only
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
// Add a predicate for finding the documents
NSString * filePattern = [NSString stringWithFormat:#"*.%#", PTK_EXTENSION];
[query setPredicate:[NSPredicate predicateWithFormat:#"%K LIKE %#",
NSMetadataItemFSNameKey, filePattern]];
}
return query;
}

Related

ios UIDocumentMenuViewController not display files

I want to import file from file list.I have used UIDocumentMenuViewController to display and select file. It shows blank screen when open iCloud.
I have created UIDocumentMenuViewController which show all types of files.
UIDocumentMenuViewController *documentPickerMenu = [[UIDocumentMenuViewController alloc]
initWithDocumentTypes:#[#"public.item"]
inMode:UIDocumentPickerModeImport];
documentPickerMenu.delegate = self;
[self presentViewController:documentPickerMenu animated:YES completion:nil];
I have implemented delegate methods.
- (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker{
documentPicker.delegate = self;
[self presentViewController:documentPicker animated:YES completion:nil]; }
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
if (controller.documentPickerMode == UIDocumentPickerModeImport)
{
// Condition called when user download the file
NSData *fileData = [NSData dataWithContentsOfURL:url];
// NSData of the content that was downloaded - Use this to upload on the server or save locally in directory
//Showing alert for success
dispatch_async(dispatch_get_main_queue(), ^{
NSString *alertMessage = [NSString stringWithFormat:#"Successfully downloaded file %#", [url lastPathComponent]];
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:#"UIDocumentView"
message:alertMessage
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alertController animated:YES completion:nil];
});
} }
I have images on iCloud.I have tried same thing by creating UIDocumentPickerViewController instead of UIDocumentMenuViewController but same issu.I am not able to identify issue can anyone have any idea?

IOS Share Extension NSMutableArray addObject Unrecognized selector sent to instance

After clicking post to the share dialog, the Host App(e.g. Safari) hangs up if arrSites variable is currently not empty. I can only store 1 object inside my arrSites variable. How can I addObject to my NSMutableArray variable?
Below is my implemented code and it generates an error in [arrSites addObject:dictSite] line.
- (void)didSelectPost
{
inputItem = self.extensionContext.inputItems.firstObject;
NSItemProvider *urlItemProvider = [[inputItem.userInfo valueForKey:NSExtensionItemAttachmentsKey] objectAtIndex:0];
if ([urlItemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypeURL])
{
NSLog(#"++++++++++ Attachment is a URL");
[urlItemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error)
{
if (error)
{
NSLog(#"Error occured");
}
else
{
NSMutableArray *arrSites;
if ([sharedUserDefaults valueForKey:#"SharedExtension"]){
arrSites = [sharedUserDefaults objectForKey:#"SharedExtension"];
}else{
arrSites = [[NSMutableArray alloc] init];
}
NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, #"Text", url.absoluteString, #"URL",nil];
[arrSites addObject:dictSite];
[sharedUserDefaults setObject:arrSites forKey:#"SharedExtension"];
[sharedUserDefaults synchronize];
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Success"
message:#"V7 Posted Successfully."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[UIView animateWithDuration:0.20 animations:^
{
self.view.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height);
}
completion:^(BOOL finished)
{
[self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
}];
}];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
}
Without memory allocation you can't add the object to array, use like
// allocate the memory of array in before
NSMutableArray *arrSites = [[NSMutableArray alloc] init];
if ([sharedUserDefaults valueForKey:#"SharedExtension"]){
[arrSites addObjectsFromArray:[sharedUserDefaults objectForKey:#"SharedExtension"]];
}
[arrSites addObject:dictSite];
Most likely the source of the problem is that
arrSites = [sharedUserDefaults objectForKey:#"SharedExtension"];
creates immutable object (NSArray instead of NSMutableArray). You can fix this issue using
arrSites = [[sharedUserDefaults objectForKey:#"SharedExtension"] mutableCopy];
instead.

Firebase Upload Image to Storage During User Registration

I'm new to Firebase, and I have been following their documentation here.
However, nothing I have tried seems to work.
What I am trying to do:
1) Register a user -Works
2) Have the user choose a profile picture during the registration process -Doesn't work.
The code:
- (void) registerNewUser:(FIRUser *)user
{
FIRUser *currentUser = [FIRAuth auth].currentUser;
NSString *email = emailAddressTxtField.text;
NSString *password = passwordTxtField.text;
NSString *username = usernameTxtField.text;
[[FIRAuth auth]
createUserWithEmail:email
password:password
completion:^(FIRUser *_Nullable user,
NSError *_Nullable error)
{
if (error)
{
NSLog(#"%#", error.localizedDescription);
return;
}
else
{
////ASSIGN NEW USER THEIR NAME////
self.databaseRef = [[FIRDatabase database] reference];
[[[databaseRef child:#"users"] child:user.uid]
setValue:#{#"name": username}];
}
}];
////ESTABLISHED A USER, SO LET'S ASSIGN THEIR PIC TO THEM////
if (profilePicImageView.image)
{
FIRStorageReference *profilePicRef = [[storageRef child:#"images/profilePicture.jpg"] child:currentUser.uid];
FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
metadata.contentType = #"image/jpeg";
NSData *imageData = UIImageJPEGRepresentation(self.profilePicImageView.image, 0.8);
NSLog(#"metadata from image: %#", metadata);
[profilePicRef putData:imageData metadata:metadata completion:^(FIRStorageMetadata *metadata, NSError *error)
{
if (error != nil)
{
NSString *profileImageURL = metadata.downloadURL.absoluteString;
NSLog(#"Profile Image URL from image: %#", profileImageURL);
[ProgressHUD showSuccess:[NSString stringWithFormat:#"%# Successfully Registered!!", username]];
[self.segmentedLoginRegister setSelectedSegmentIndex:0];
[self checkSegmentedControl];
[ProgressHUD showSuccess:[NSString stringWithFormat:#"Welcome %#!", username]];
}
else
{
NSLog(#"Failed to Register User with profile image");
}
}];
}
}
Additional Information:
Photos are coming only from the camera roll of the user's device
Debug area prints:
[Generic] Creating an image format with an unknown type is an error
My guess is that profilePicImageView.image doesn't actually contain a valid image object.
HOW TO REGISTER A USER
Let's assume that you have 3 textfields to register a user. You have a usernameTextfield, an emailTextField, and a passwordTextfield. We also want to have a profilePicture associated with this user. So we first:
Established a method to save our values for our User to the Firebase Database:
-(void) saveValuesForUser:(FIRUser *) user
{
NSString *username = usernameTxtField.text;
self.databaseRef = [[FIRDatabase database] reference];
[[[databaseRef child:#"users"] child:user.uid]
setValue:#{#"Name": username, #"Profile Picture": profileImageURL}];
}
The profileImageURL above is an NSString that you can create above your implementation of your view controller, but we also should create a UIImage that we can access throughout the ViewController:
#import "ViewController.h"
#import Photos;
#interface ViewController ()
#end
NSString *profileImageURL;
UIImage *profileImage;
#implementation ViewController
I'm guessing that you know how to launch the camera roll off from a UIButton but in case you do not, let's call these methods so that when our user taps the button to choose their image that it get's set to our profilePicture.imageView:
- (IBAction)chooseImageAction:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
picker.delegate = self;
profileImage = info[UIImagePickerControllerEditedImage];
profilePicImageView.image = profileImage;
[self dismissViewControllerAnimated:NO completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
Now we're cooking with fire! Now that we have the image the user wants to upload for their profilePicture, let's create a method to save it as an NSURL to our Firebase Database:
- (void) saveProfileImage
{
FIRUser *currentUser = [FIRAuth auth].currentUser;
NSString *username = usernameTxtField.text;
if (profilePicImageView.image != nil)
{
FIRStorage *storage = [FIRStorage storage];
storageRef = [storage referenceForURL:#"gs://PUTYOURFIREBASEHERE.appspot.com"];
NSString *imageID = [[NSUUID UUID] UUIDString];
NSString *imageName = [NSString stringWithFormat:#"Profile Pictures/%#.jpg",imageID];
FIRStorageReference *profilePicRef = [storageRef child:imageName];
FIRStorageMetadata *metadata = [[FIRStorageMetadata alloc] init];
metadata.contentType = #"image/jpeg";
NSData *imageData = UIImageJPEGRepresentation(self.profilePicImageView.image, 0.8);
[profilePicRef putData:imageData metadata:metadata completion:^(FIRStorageMetadata *metadata, NSError *error)
{
if (!error)
{
profileImageURL = metadata.downloadURL.absoluteString;
[self saveValuesForUser: currentUser];
}
else if (error)
{
NSLog(#"Failed to Register User with profile image");
}
}];
}
}
IMPORTANT: Make sure you insert your gs:// reference for the value of storageRef! You can find this on your Firebase Console under Storage.
Now that we have the method to save the user's profile picture, let's create a method to Register the new user that we can call it on our IBAction:
- (void) registerNewUser
{
NSString *email = emailAddressTxtField.text;
NSString *password = passwordTxtField.text;
[[FIRAuth auth]
createUserWithEmail:email
password:password
completion:^(FIRUser *_Nullable user,
NSError *_Nullable error)
{
if (error)
{
NSLog(#"%#", error.localizedDescription);
return;
}
else
{
[self saveProfileImage];
}
}];
}
Oh thats nice! Now, let's call that method on our button, so that when the user taps the Register button on our UI, that it get's called:
- (IBAction)registerUserAction:(id)sender
{
[self registerNewUser];
}
Note: Make sure that in your ViewController.h file that you are setting the appropriate delegates:
#interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate>

App is Not asking contact permission to access contact in iOS 9

I am using The Following code for getting iPhone Contacts but my App is not getting Permission For Allow Contacts in iOS 9 . I have found this code from stack and the other references are also same .
- (void)getPersonOutOfAddressBook
{
//1
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil) {
NSLog(#"Succesful.");
//2
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
//3
NSUInteger i = 0; for (i = 0; i < [allContacts count]; i++)
{
NSMutableDictionary *persiondict =[[NSMutableDictionary alloc]init] ;
// Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
//4
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson,
kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:#"%# %#", firstName, lastName];
// person.firstName = firstName;
// person.lastName = lastName;
// person.fullName = fullName;
[persiondict setValue:fullName forKey:#"fullName"] ;
//email
//5
ABMultiValueRef emails = ABRecordCopyValue(contactPerson, kABPersonEmailProperty);
//6
NSUInteger j = 0;
for (j = 0; j < ABMultiValueGetCount(emails); j++) {
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
if (j == 0) {
// person.homeEmail = email;
[persiondict setValue:email forKey:#"email"] ;
// NSLog(#"person.homeEmail = %# ", person.homeEmail);
}
else if (j==1)
[persiondict setValue:email forKey:#"email"] ;
}
//7
[ArrUserOfContacts addObject:persiondict];
}
//8
CFRelease(addressBook);
} else {
//9
NSLog(#"Error reading Address Book");
}
}
I am unable to find problem here , How can user get an permission for access contacts . Any Suggestion Will be helpfull .
ABAddressBookRequestAccessWithCompletion is deprecated in iOS 9. Now you should use Contacts framework. This is an example in Objective C:
CNContactStore * contactStore = [CNContactStore new];
[contactStore requestAccessForEntityType:entityType completionHandler:^(BOOL granted, NSError * _Nullable error) {
if(granted){
//
}
}];
In Swift 3:
CNContactStore().requestAccess(for: .contacts, completionHandler: { granted, error in
if (granted){
//
}
})
This will only ask for permission if the user hasn't denied or approved permissions for contacts in your app. You can't ask for permissions that have already been denied by the user (At least now in iOS 10), what you can do is redirect the user to Settings.
You need request permissions using ABAddressBookRequestAccessWithCompletion()
ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
if (!granted){
NSLog(#"Just denied");
return;
}
NSLog(#"Just authorized");
});
If you want to check user given contacts permission or not and, if permission is not given then show alert to move user in settings to give permission.
Then use the following function checkContactsPermission as:
-(void)checkContactsPermission {
//Check permission status
switch (ABAddressBookGetAuthorizationStatus()) {
case kABAuthorizationStatusAuthorized:
// Already permission given
break;
case kABAuthorizationStatusDenied:{
// Permission not given so move user in settings page to app.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Alert!" message:#"his app requires access to your contacts." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* SettingsButton = [UIAlertAction actionWithTitle:#"Settings"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSURL * settingsURL = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"%#%#",UIApplicationOpenSettingsURLString,[[NSBundle mainBundle]bundleIdentifier]]];
if (settingsURL) {
[[UIApplication sharedApplication] openURL:settingsURL];
}
}];
UIAlertAction* DeniedButton = [UIAlertAction actionWithTitle:#"Denied"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
[alert addAction:SettingsButton];
[alert addAction:DeniedButton];
[self presentViewController:alert animated:YES completion:nil];
}
case kABAuthorizationStatusRestricted: {
// Permission not given so move user in settings page to app.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Alert!" message:#"his app requires access to your contacts." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* SettingsButton = [UIAlertAction actionWithTitle:#"Settings"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSURL * settingsURL = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"%#%#",UIApplicationOpenSettingsURLString,[[NSBundle mainBundle]bundleIdentifier]]];
if (settingsURL) {
[[UIApplication sharedApplication] openURL:settingsURL];
}
}];
UIAlertAction* DeniedButton = [UIAlertAction actionWithTitle:#"Denied"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
}];
[alert addAction:SettingsButton];
[alert addAction:DeniedButton];
[self presentViewController:alert animated:YES completion:nil];
}
break;
case kABAuthorizationStatusNotDetermined:
// Permission not determin. so request for permission.
ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
if (granted){
// Already permission given
}
});
break;
}
}
for iOS 10 you can use Contacts framework for check permission.

uploadedFile not called

I have an app where I upload a simple .csv file to Dropbox. The files upload perfectly when I send them, but the restClient uploadedFile method is not called. I would like this to use this to display to the user that the file has been uploaded successfully. I seem to remeber it was called the first few times I ran the code, but then it stopped and I can't see why.
Here are some snippets:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) //Cancel
{
}
else if (buttonIndex == 1) //Send
{
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *CCD = [docPath stringByAppendingPathComponent:#"CCD.csv"];
if ([[NSFileManager defaultManager] fileExistsAtPath:CCD])
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *machineName = [defaults objectForKey:#"machineName"];
NSString *fileTitle = [defaults stringForKey:#"setTitle"];
NSMutableString *filePath = [NSMutableString string];
[filePath appendString:docPath];
[filePath appendString:#"/CCD.csv"];
NSString *destDir = #"/";
[SVProgressHUD showWithStatus:[NSString stringWithFormat:#"Sending to %#...", machineName]];
[[self restClient] uploadFile:fileTitle toPath:destDir
withParentRev:nil fromPath:filePath];
}
}
}
- (void)restClient:(DBRestClient*)restClient uploadedFile:(NSString*)filePath {
NSLog(#"File uploaded successfully");
[SVProgressHUD dismiss];
};
As I said, it uploads the file perfectly, I just don't get the call to the uploadedFile method.
Try this way..
#interface ResultClass_vice : UIViewController<DBRestClientDelegate>
{
DBRestClient *restClient;
}
#pragma mark - DropBox
- (void)didPressLink {
// [[DBSession sharedSession]unlinkAll];
if (![[DBSession sharedSession] isLinked]) {
[[DBSession sharedSession] linkFromController:self];
// Session must be linked before creating any DBRestClient objects.
// nstr
UIAlertView *al=[[UIAlertView alloc]initWithTitle:#"" message:#"You must have to Login" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[al show];
[al release];
}
}
- (DBRestClient *)restClient {
if (!restClient) {
restClient =
[[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
restClient.delegate = self;
}
return restClient;
}
- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
//NSLog(#"File uploaded successfully to path: %#", metadata.path);
UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:#"Success" message:#"Your file is successfully uploaded to Dropbox" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil]retain];
[alert show];
[alert release];
}
- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error {
NSLog(#"File upload failed with error - %#", error);
}
Let me know if you have any problem because I already implemented it.
The main problem is you have changed upload method parameters:
You are using:
- (void)restClient:(DBRestClient*)restClient uploadedFile:(NSString*)filePath {
NSLog(#"File uploaded successfully to path: %#", metadata.path);
}
And you should used:
- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
NSLog(#"File uploaded successfully to path: %#", metadata.path);
}
If you change the number of parameters, you are creating a new function, and therefore, Dropbox SDK will not called it.
I hope this would be helpful

Resources