Upload Files to Dropbox from iOS App with Swift

Unable to show list and upload file from dropbox in swift 5

[Cross-linking for reference: https://www.dropboxforum.com/t5/Discuss-Dropbox-Developer-API/Unable-to-upload-file-from-my-ios-app/m-p/533160 ]

This "Your app is not permitted to access this endpoint" error indicates that the app for the access token you're using to make the call does not have the necessary scope needed for calling that particular endpoint. As indicated by the error message in this case, the app would need the "files.metadata.read" scope.

You can add it via the "Permissions" tab on the app's info page on the App Console. Then you can get a new access token with that scope added and use that new access token to make this API call.

Can swift write a file to a Dropbox folder's URL without using Swifty Dropbox SDK/API?

ANSWER IS: NO.

WORKAROUND IS: Instead, use: Swifty DropBox SDK and API

Dropbox API v2 for uploading media files in iOS

  1. The "/test/path/in/Dropbox/account/my_output.txt" in the sample is just an example. You should supply the path for the desired location of the uploaded file in the Dropbox account. If you're using an app folder app, the root you supply will automatically be translated into the app folder itself. For example, if you have an app folder at "/Apps/MyAppName", and you want to upload a file named "video.mp4" into a folder called "Videos" in your app folder, you should supply a path value of "/Videos/video.mp4". That will automatically become /Apps/MyAppName/Videos/video.mp4 in the account.

  2. The sample makes an NSData by encoding a string, but you can use the same uploadData to upload a file from any NSData.

iOS - Dropbox upload to App Folder

We must be very careful how you are initilazing the DBSession. as mentioned by "omz" in above comments, we have to provide appropriate key if its kDBRootDropbox or kDBRootAppFolder. In my case I'm using 2 different types of accounts which is the main reason for failure.

I'm very thankful to "omz"

How to upload/download a file from/to dropbox using Xcode

Let me help you in this case, I have created Wrapper class for Dropbox find code below used in one of my project. It does not support ARC. Create DropBoxManager header and implementation file
This may be too much for you if you are beginner but try to read whole answer and follow step by step. Let me know in case of any problem, I will help.

Code for DropBoxManager.h

#import <Foundation/Foundation.h>
#import <DropboxSDK/DropboxSDK.h>

#define kDropbox_AppKey @"" // Provide your key here
#define kDropbox_AppSecret @"" // Provide your secret key here
#define kDropbox_RootFolder kDBRootDropbox //Decide level access like root or app

@protocol DropBoxDelegate;

typedef enum
{
DropBoxTypeStatusNone = 0,
DropBoxGetAccountInfo = 1,
DropBoxGetFolderList = 2,
DropBoxCreateFolder = 3,
DropBoxUploadFile = 4
} DropBoxPostType;

@interface DropboxManager : NSObject <DBRestClientDelegate,DBSessionDelegate,UIAlertViewDelegate>
{
UIViewController<DropBoxDelegate> *apiCallDelegate;

DBSession *objDBSession;
NSString *relinkUserId;
DBRestClient *objRestClient;

DropBoxPostType currentPostType;

NSString *strFileName;
NSString *strFilePath;
NSString *strDestDirectory;
NSString *strFolderCreate;
NSString *strFolderToList;
}

@property (nonatomic,retain) DBSession *objDBSession;
@property (nonatomic,retain) NSString *relinkUserId;

@property (nonatomic,assign) UIViewController<DropBoxDelegate> *apiCallDelegate;

@property (nonatomic,retain) DBRestClient *objRestClient;

@property (nonatomic,assign) DropBoxPostType currentPostType;

@property (nonatomic,retain) NSString *strFileName;
@property (nonatomic,retain) NSString *strFilePath;
@property (nonatomic,retain) NSString *strDestDirectory;

@property (nonatomic,retain) NSString *strFolderCreate;

@property (nonatomic,retain) NSString *strFolderToList;

//Singleton
+(id)dropBoxManager;

//Initialize dropbox
-(void)initDropbox;

//Authentication Verification
-(BOOL)handledURL:(NSURL*)url;
-(void)dropboxDidLogin;
-(void)dropboxDidNotLogin;

//Upload file
-(void)uploadFile;

//Download File
-(void)downlaodFileFromSourcePath:(NSString*)pstrSourcePath destinationPath:(NSString*)toPath;

//Create Folder
-(void)createFolder;

//Get Account Information
-(void)loginToDropbox;
-(void)logoutFromDropbox;
-(BOOL)isLoggedIn;

//List Folders
-(void)listFolders;

@end

@protocol DropBoxDelegate <NSObject>

@optional

- (void)finishedLogin:(NSMutableDictionary*)userInfo;
- (void)failedToLogin:(NSString*)withMessage;

- (void)finishedCreateFolder;
- (void)failedToCreateFolder:(NSString*)withMessage;

- (void)finishedUploadFile;
- (void)failedToUploadFile:(NSString*)withMessage;

- (void)finishedDownloadFile;
- (void)failedToDownloadFile:(NSString*)withMessage;

- (void)getFolderContentFinished:(DBMetadata*)metadata;
- (void)getFolderContentFailed:(NSString*)withMessage;

@end

Code for DropBoxManager.m

#import "DropboxManager.h"

@implementation DropboxManager

@synthesize objDBSession,relinkUserId,apiCallDelegate;
@synthesize objRestClient;
@synthesize currentPostType;

@synthesize strFileName;
@synthesize strFilePath;
@synthesize strDestDirectory;

@synthesize strFolderCreate;

@synthesize strFolderToList;

static DropboxManager *singletonManager = nil;

+(id)dropBoxManager
{
if(!singletonManager)
singletonManager = [[DropboxManager alloc] init];

return singletonManager;
}

-(void)initDropbox
{
DBSession* session = [[DBSession alloc] initWithAppKey:kDropbox_AppKey appSecret:kDropbox_AppSecret root:kDropbox_RootFolder];
session.delegate = self;
[DBSession setSharedSession:session];
[session release];

if([[DBSession sharedSession] isLinked] && objRestClient == nil)
{
self.objRestClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
self.objRestClient.delegate = self;
}
}

-(void)checkForLink
{
if(![[DBSession sharedSession] isLinked])
[[DBSession sharedSession] linkFromController:apiCallDelegate];
}

-(BOOL)handledURL:(NSURL*)url
{
BOOL isLinked=NO;
if ([[DBSession sharedSession] handleOpenURL:url])
{

if([[DBSession sharedSession] isLinked])
{
isLinked=YES;
[self dropboxDidLogin];
}
else
{
isLinked = NO;
[self dropboxDidNotLogin];
}
}
return isLinked;
}

#pragma mark -
#pragma mark Handle login

-(void)dropboxDidLogin
{
NSLog(@"Logged in");

if([[DBSession sharedSession] isLinked] && self.objRestClient == nil)
{
self.objRestClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
self.objRestClient.delegate = self;
}

switch(currentPostType)
{
case DropBoxTypeStatusNone:

break;

case DropBoxGetAccountInfo:
[self loginToDropbox];
break;

case DropBoxGetFolderList:
[self listFolders];
break;

case DropBoxCreateFolder:
[self createFolder];
break;

case DropBoxUploadFile:
[self uploadFile];
break;
}

//[(MainViewController*)apiCallDelegate setLoginStatus];
}

-(void)dropboxDidNotLogin
{
NSLog(@"Not Logged in");
switch(currentPostType)
{
case DropBoxTypeStatusNone:

break;

case DropBoxUploadFile:
if([self.apiCallDelegate respondsToSelector:@selector(failedToUploadFile:)])
[self.apiCallDelegate failedToUploadFile:@"Problem connecting dropbox. Please try again later."];
break;

case DropBoxGetFolderList:

break;

case DropBoxCreateFolder:

break;

case DropBoxGetAccountInfo:

break;
}
}

#pragma mark -
#pragma mark DBSessionDelegate methods

- (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
{
relinkUserId = [userId retain];
[[[[UIAlertView alloc] initWithTitle:@"Dropbox Session Ended" message:@"Do you want to relink?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Relink", nil] autorelease] show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)index
{
if (index != alertView.cancelButtonIndex)
[[DBSession sharedSession] linkUserId:relinkUserId fromController:apiCallDelegate];

[relinkUserId release];
relinkUserId = nil;
}

#pragma mark -
#pragma mark Fileupload

-(void)uploadFile
{
if([[DBSession sharedSession] isLinked])
[self.objRestClient uploadFile:strFileName toPath:strDestDirectory withParentRev:nil fromPath:strFilePath];
else
[self checkForLink];
}

-(void)downlaodFileFromSourcePath:(NSString*)pstrSourcePath destinationPath:(NSString*)toPath
{
if([[DBSession sharedSession] isLinked])
[self.objRestClient loadFile:pstrSourcePath intoPath:toPath];
else
[self checkForLink];
}

- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath from:(NSString*)srcPath metadata:(DBMetadata*)metadata
{
if([self.apiCallDelegate respondsToSelector:@selector(finishedUploadeFile)])
[self.apiCallDelegate finishedUploadFile];

NSLog(@"File uploaded successfully to path: %@", metadata.path);
}

- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)destPath contentType:(NSString*)contentType
{
if([self.apiCallDelegate respondsToSelector:@selector(finishedDownloadFile)])
[self.apiCallDelegate finishedDownloadFile];
}

-(void)restClient:(DBRestClient *)client loadFileFailedWithError:(NSError *)error
{
if([self.apiCallDelegate respondsToSelector:@selector(failedToDownloadFile:)])
[self.apiCallDelegate failedToDownloadFile:[error description]];
}

- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error
{
if([self.apiCallDelegate respondsToSelector:@selector(failedToUploadFile:)])
[self.apiCallDelegate failedToUploadFile:[error description]];

NSLog(@"File upload failed with error - %@", error);
}

#pragma mark -
#pragma mark Create Folder

-(void)createFolder
{
if([[DBSession sharedSession] isLinked])
[self.objRestClient createFolder:strFolderCreate];
else
[self checkForLink];
}

- (void)restClient:(DBRestClient*)client createdFolder:(DBMetadata*)folder
{
if([self.apiCallDelegate respondsToSelector:@selector(finishedCreateFolder)])
[self.apiCallDelegate finishedCreateFolder];

NSLog(@"Folder created successfully to path: %@", folder.path);
}

- (void)restClient:(DBRestClient*)client createFolderFailedWithError:(NSError*)error
{
if([self.apiCallDelegate respondsToSelector:@selector(failedToCreateFolder:)])
[self.apiCallDelegate failedToCreateFolder:[error description]];

NSLog(@"Folder create failed with error - %@", error);
}

#pragma mark -
#pragma mark Load account information

-(void)loginToDropbox
{
if([[DBSession sharedSession] isLinked])
[self.objRestClient loadAccountInfo];
else
[self checkForLink];
}

- (void)restClient:(DBRestClient*)client loadedAccountInfo:(DBAccountInfo*)info
{
if([self.apiCallDelegate respondsToSelector:@selector(finishedLogin:)])
{
NSMutableDictionary *userInfo = [[[NSMutableDictionary alloc] init] autorelease];
[userInfo setObject:info.displayName forKey:@"UserName"];
[userInfo setObject:info.userId forKey:@"UserID"];
[userInfo setObject:info.referralLink forKey:@"RefferelLink"];
[self.apiCallDelegate finishedLogin:userInfo];
}

NSLog(@"Got Information: %@", info.displayName);
}

- (void)restClient:(DBRestClient*)client loadAccountInfoFailedWithError:(NSError*)error
{
if([self.apiCallDelegate respondsToSelector:@selector(failedToLogin:)])
[self.apiCallDelegate failedToLogin:[error description]];

NSLog(@"Failed to get account information with error - %@", error);
}

#pragma mark -
#pragma mark Logout

-(void)logoutFromDropbox
{
[[DBSession sharedSession] unlinkAll];
[self.objRestClient release];
}

#pragma mark -
#pragma mark Check for login

-(BOOL)isLoggedIn
{
return [[DBSession sharedSession] isLinked] ? YES : NO;
}

#pragma mark -
#pragma mark Load Folder list

-(void)listFolders
{
NSLog(@"Here-->%@",self.strFolderToList);
if([[DBSession sharedSession] isLinked])
[self.objRestClient loadMetadata:self.strFolderToList];
else
[self checkForLink];
}

- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata
{
if (metadata.isDirectory)
{
NSLog(@"Folder '%@' contains:", metadata.contents);
for (DBMetadata *file in metadata.contents)
{
NSLog(@"\t%@", file);
}

if([apiCallDelegate respondsToSelector:@selector(getFolderContentFinished:)])
[apiCallDelegate getFolderContentFinished:metadata];
}
NSLog(@"Folder list success: %@", metadata.path);

}

- (void)restClient:(DBRestClient*)client metadataUnchangedAtPath:(NSString*)path
{

}

- (void)restClient:(DBRestClient*)client loadMetadataFailedWithError:(NSError*)error
{
NSLog(@"Load meta data failed with error - %@", error);

if([apiCallDelegate respondsToSelector:@selector(getFolderContentFailed:)])
[apiCallDelegate getFolderContentFailed:[error localizedDescription]];
}

E.g. usage header file

//Your view controller Header file.
#import <UIKit/UIKit.h>
#import "DropboxManager.h"

@interface YourViewController : UIViewController <DropBoxDelegate>
{
DropboxManager *objManager;
}

@property (nonatomic,assign) DropboxManager *objManager;

-(IBAction)btnUploadFileTapped:(id)sender;

@end

E.g. usage implementation file

#import "YourViewController.h"

@implementation YourViewController
@synthesize objManager;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];

objManager = [DropboxManager dropBoxManager];
objManager.apiCallDelegate =self;
[objManager initDropbox];
}

-(IBAction)btnUploadFileTapped:(id)sender
{
objManager.currentPostType = DropBoxUploadFile;
objManager.strFileName = @"YourFileName";
objManager.strFilePath = @"YourFilePath";
objManager.strDestDirectory = @"/";
[objManager uploadFile];
}

#pragma mark -
#pragma mark File upload delegate

- (void)finishedUploadFile
{
NSLog(@"Uploaded successfully.");
}

- (void)failedToUploadFile:(NSString*)withMessage
{
NSLog(@"Failed to upload error is %@",withMessage);
}

@end


Related Topics



Leave a reply



Submit