- Notifications
You must be signed in to change notification settings - Fork0
Official Objective-C SDK for the Dropbox API v2.
License
JavaScriptBach/dropbox-sdk-obj-c
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
The Official Dropbox Objective-C SDK for integrating with DropboxAPI v2 on iOS or macOS.
Full documentationhere.
NOTE: Please do not rely onmaster in production. Please instead use one of our taggedrelease commits (preferrably fetched via CocoaPods or Carthage), as these commits have been more thoroughly tested.
- System requirements
- Get started
- SDK distribution
- Configure your project
- Try some API requests
- Examples
- Migrating from API v1
- Documentation
- Stone
- Modifications
- Bugs
- iOS 9.0+
- macOS 10.10+
- Xcode 8+
The Dropbox Objective-C SDK currently supports Xcode 8 and iOS 10. However, there appears to be a bug with the Keychain in the iOS simulator environment where data is not persistently saved to the Keychain.
As a temporary workaround, in the Project Navigator, selectyour project >Capabilities >Keychain Sharing >ON.
You can read more about the bughere.
Currently, there is a bug with iOS 10 where our longpoll requests timeout after ~6 minutes (instead of our max supported timeframe of 8 minutes (480 seconds)).
For this reason, we recommend that all longpoll calls be made using-listFolderLongpoll:timeout:, with a specifiedtimeout values of <= 300 seconds (5 minutes), until this issue is resolved by Apple.
Read more about the issuehere.
Before using this SDK, you should register your application in theDropbox App Console. This creates a record of your app with Dropbox that will be associated with the API calls you make.
All requests need to be made with an OAuth 2.0 access token. An OAuth token represents an authenticated link between a Dropbox app anda Dropbox user account or team.
Once you've created an app, you can go to the App Console and manually generate an access token to authorize your app to access your own Dropbox account.Otherwise, you can obtain an OAuth token programmatically using the SDK's pre-defined auth flow. For more information,see below.
You can integrate the Dropbox Objective-C SDK into your project using one of several methods.
To useCocoaPods, a dependency manager for Cocoa projects, you should first install it using the following command:
$ gem install cocoapods
Then navigate to the directory that contains your project and create a new file calledPodfile. You can do this either withpod init, or open an existing Podfile, and then addpod 'ObjectiveDropboxOfficial' to the main loop. Your Podfile should look something like this:
platform:ios,'9.0'use_frameworks!target'<YOUR_PROJECT_NAME>'dopod'ObjectiveDropboxOfficial'end
platform:osx,'10.10'use_frameworks!target'<YOUR_PROJECT_NAME>'dopod'ObjectiveDropboxOfficial'end
Then, after ensuring that your project window in Xcode isclosed, run the following command to install the dependency:
$ pod install
Once this command completes, open the newly create.xcworkspace file. Your project should now be successfully integrated with the the SDK.
From here, you can pull SDK updates using the following command:
$ pod update
If Xcode errors with a message aboutUndefined symbols for architecture..., try the following:
- Project Navigator > build target >Build Settings >Other Linker Flags add
$(inherited)and-ObjC.
You can also integrate the Dropbox Objective-C SDK into your project usingCarthage, a decentralized dependency manager for Cocoa. Carthage offers more flexibility than CocoaPods, but requires some additional work. You can install Carthage (with Xcode 7+) viaHomebrew:
brew updatebrew install carthage
To install the Dropbox Objective-C SDK via Carthage, you need to create aCartfile in your project with the following contents:
# ObjectiveDropboxOfficialgithub "https://github.com/dropbox/dropbox-sdk-obj-c" ~> 3.7.0Then, run the following command to checkout and build the Dropbox Objective-C SDK repository:
carthage update --platform iOS
In the Project Navigator in Xcode, select your project, and then navigate toGeneral >Linked Frameworks and Libraries, then drag and dropObjectiveDropboxOfficial.framework (fromCarthage/Build/iOS).
Then, navigate toBuild Phases >+ >New Run Script Phase. In the newly-createdRun Script section, add the following code to the script body area (beneath the "Shell" box):
/usr/local/bin/carthage copy-frameworksThen, navigate to theInput Files section and add the following path:
$(SRCROOT)/Carthage/Build/iOS/ObjectiveDropboxOfficial.frameworkcarthage update --platform Mac
In the Project Navigator in Xcode, select your project, and then navigate toGeneral >Embedded Binaries, then drag and dropObjectiveDropboxOfficial.framework (fromCarthage/Build/Mac).
Then navigate toBuild Phases >+ >New Copy Files Phase. In the newly-createdCopy Files section, click theDestination drop-down menu and selectProducts Directory, then drag and dropObjectiveDropboxOfficial.framework.dSYM (fromCarthage/Build/Mac).
Please make sure the SDK is inside of your Xcode project folder, otherwise your app may run into linking errors.
If you wish to keep the SDK outside of your Xcode project folder (perhaps to share between different apps), you will need to configure your a few environmental variables.
Project Navigator > build target >Build Settings >Header Search Path add
$(PROJECT_DIR)/../<PATH_TO_SDK>/dropbox-sdk-obj-c/Source/ObjectiveDropboxOfficial (recursive)Project Navigator > build target >Build Settings >Framework Search Paths add
$(PROJECT_DIR)/../<PATH_TO_SDK>/dropbox-sdk-obj-c/Source/ObjectiveDropboxOfficial/build/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) (non-recursive)
If you receive a run-time error message likedyld: Library not loaded:, please try the following:
- Add ObjectiveDropboxOfficial framework toEmbedded Binaries as well asLinked Frameworks and Libraries.
- Project Navigator > build target >Build Settings >Linking >Runpath Search Paths add
$(inherited) @executable_path/Frameworks.
Finally, you can also integrate the Dropbox Objective-C SDK into your project manually with the help of Carthage. Please take the following steps:
Create aCartfile in your project with the same contents as the Cartfile listed in theCarthage section of the README.
Then, run the following command to checkout and build the Dropbox Objective-C SDK repository:
carthage update --platform iOS
Once you have checked-out out all the necessary code via Carthage, drag theCarthage/Checkouts/ObjectiveDropboxOfficial/Source/ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.xcodeproj file into your project as a subproject.
Then, in the Project Navigator in Xcode, select your project, and then navigate to your project's build target >General >Linked Frameworks and Libraries >+ and then add theObjectiveDropboxOfficial.framework file for the iOS platform.
carthage update --platform Mac
Once you have checked-out out all the necessary code via Carthage, drag theCarthage/Checkouts/ObjectiveDropboxOfficial/Source/ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.xcodeproj file into your project as a subproject.
Then, in the Project Navigator in Xcode, select your project, and then navigate to your project's build target >General >Embedded Binaries >+ and then add theObjectiveDropboxOfficial.framework file for the macOS platform.
Once you have integrated the Dropbox Objective-C SDK into your project, there are a few additional steps to take before you can begin making API calls.
You will need to modify your application's.plist to handle Apple'snew security changes to thecanOpenURL function. You shouldadd the following code to your application's.plist file:
<key>LSApplicationQueriesSchemes</key> <array> <string>dbapi-8-emm</string> <string>dbapi-2</string> </array>This allows the Objective-C SDK to determine if the official Dropbox iOS app is installed on the current device. If it is installed, then the official Dropbox iOS app can be used to programmatically obtain an OAuth 2.0 access token.
Additionally, your application needs to register to handle a unique Dropbox URL scheme for redirect following completion of the OAuth 2.0 authorization flow. This URL scheme should have the formatdb-<APP_KEY>, where<APP_KEY> is yourDropbox app's app key, which can be found in theApp Console.
You should add the following code to your.plist file (but be sure to replace<APP_KEY> with your app's app key):
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>db-<APP_KEY></string> </array> <key>CFBundleURLName</key> <string></string> </dict> </array>After you've made the above changes, your application's.plist file should look something like this:
There are three methods to programmatically retrieve an OAuth 2.0 access token:
- Direct auth (iOS only): This launches the official Dropbox iOS app (if installed), authenticates via the official app, then redirects back into the SDK
- Safari view controller auth (iOS only): This launches a
SFSafariViewControllerto facillitate the auth flow. This is desirable because it is safer for the end-user, and pre-existing session data can be used to avoid requiring the user to re-enter their Dropbox credentials. - Redirect to external browser (macOS only): This launches the user's default browser to facillitate the auth flow. This is also desirable because it is safer for the end-user, and pre-existing session data can be used to avoid requiring the user to re-enter their Dropbox credentials.
To facilitate the above authorization flows, you should take the following steps:
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [DBClientsManagersetupWithAppKey:@"<APP_KEY>"];returnYES;}
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { [DBClientsManagersetupWithAppKeyDesktop:@"<APP_KEY>"];}
You can commence the auth flow by callingauthorizeFromController:controller:openURL method in your application'sview controller.
Please ensure that the supplied view controller is the top-most controller, so that the authorization view displays correctly.
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>- (void)myButtonInControllerPressed { [DBClientsManagerauthorizeFromController:[UIApplicationsharedApplication]controller:[[selfclass]topMostController]openURL:^(NSURL *url) { [[UIApplicationsharedApplication]openURL:url]; }];}+ (UIViewController*)topMostController{ UIViewController *topController = [UIApplicationsharedApplication].keyWindow.rootViewController;while (topController.presentedViewController) { topController = topController.presentedViewController; }return topController;}
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>- (void)myButtonInControllerPressed { [DBClientsManagerauthorizeFromControllerDesktop:[NSWorkspacesharedWorkspace]controller:[[selfclass]topMostController]openURL:^(NSURL *url){ [[NSWorkspacesharedWorkspace]openURL:url]; }];}+ (UIViewController*)topMostController{ UIViewController *topController = [UIApplicationsharedApplication].keyWindow.rootViewController;while (topController.presentedViewController) { topController = topController.presentedViewController; }return topController;}
Beginning the authentication flow on mobile will launch a window like this:
To handle the redirection back into the Objective-C SDK once the authentication flow is complete, you should add the following code in your application's delegate:
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { DBOAuthResult *authResult = [DBClientsManagerhandleRedirectURL:url];if (authResult !=nil) {if ([authResultisSuccess]) {NSLog(@"Success! User is logged into Dropbox."); }elseif ([authResultisCancel]) {NSLog(@"Authorization flow was manually canceled by user!"); }elseif ([authResultisError]) {NSLog(@"Error:%@", authResult); } }returnNO;}
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>// generic launch handler- (void)applicationWillFinishLaunching:(NSNotification *)notification { [[NSAppleEventManagersharedAppleEventManager]setEventHandler:selfandSelector:@selector(handleAppleEvent:withReplyEvent:)forEventClass:kInternetEventClassandEventID:kAEGetURL];}// custom handler- (void)handleAppleEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {NSURL *url = [NSURLURLWithString:[[eventparamDescriptorForKeyword:keyDirectObject]stringValue]]; DBOAuthResult *authResult = [DBClientsManagerhandleRedirectURL:url];if (authResult !=nil) {if ([authResultisSuccess]) {NSLog(@"Success! User is logged into Dropbox."); }elseif ([authResultisCancel]) {NSLog(@"Authorization flow was manually canceled by user!"); }elseif ([authResultisError]) {NSLog(@"Error:%@", authResult); }// this forces your app to the foreground, after it has handled the browser redirect [[NSRunningApplicationcurrentApplication]activateWithOptions:(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)]; }}
After the end user signs in with their Dropbox login credentials on mobile, they will see a window like this:
If they pressAllow orCancel, thedb-<APP_KEY> redirect URL will be launched from the view controller, and will be handled in your applicationdelegate'sapplication:handleOpenURL method, from which the result of the authorization can be parsed.
Now you're ready to begin making API requests!
Once you have obtained an OAuth 2.0 token, you can try some API v2 calls using the Objective-C SDK.
Start by creating a reference to theDBUserClient orDBTeamClient instance that you will use to make your API calls.
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>// Reference after programmatic auth flowDBUserClient *client = [DBClientsManagerauthorizedClient];
or
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>// Initialize with manually retrieved auth tokenDBUserClient *client = [[DBUserClientalloc]initWithAccessToken:@"<MY_ACCESS_TOKEN>"];
The DropboxUser API andBusiness API have three types of requests: RPC, Upload and Download.
The response handlers for each request type are similar to one another. The arguments for the handler blocks are as follows:
- route result type (
DBNilObjectif the route does not have a return type) - route-specific error (usually a union type)
- network request error (generic to all requests -- contains information like request ID, HTTP status code, etc.)
- output content (
NSURL/NSDatareference to downloaded output for Download-style endpoints only)
Response handlers are required for all endpoints. Progress handlers, on the other hand, are optional for all endpoints.
Note: The Objective-C SDK uses
NSNumberobjects in place of boolean values. This is done so that nullability can be represented in some of our API response values. For this reason, you should be careful when writing checks likeif (myAPIObject.isSomething), which is checking nullability rather than value. Instead, you should useif ([myAPIObject.isSomething boolValue]), which converts theNSNumberfield to a boolean value before using it in the if check.
[[client.filesRoutescreateFolder:@"/test/path/in/Dropbox/account"]setResponseBlock:^(DBFILESFolderMetadata *result, DBFILESCreateFolderError *routeError, DBRequestError *networkError) {if (result) {NSLog(@"%@\n", result); }else {NSLog(@"%@\n%@\n", routeError, networkError); } }];
Here's an example for listing a folder's contents. In the response handler, we repeatedly calllistFolderContinue: (for large folders) until we've listed the entire folder:
[[client.filesRouteslistFolder:@"/test/path/in/Dropbox/account"]setResponseBlock:^(DBFILESListFolderResult *response, DBFILESListFolderError *routeError, DBRequestError *networkError) {if (response) {NSArray<DBFILESMetadata *> *entries = response.entries;NSString *cursor = response.cursor;BOOL hasMore = [response.hasMoreboolValue]; [selfprintEntries:entries];if (hasMore) {NSLog(@"Folder is large enough where we need to call `listFolderContinue:`"); [selflistFolderContinueWithClient:clientcursor:cursor]; }else {NSLog(@"List folder complete."); } }else {NSLog(@"%@\n%@\n", routeError, networkError); } }];.........- (void)listFolderContinueWithClient:(DBUserClient *)client cursor:(NSString *)cursor { [[client.filesRouteslistFolderContinue:cursor]setResponseBlock:^(DBFILESListFolderResult *response, DBFILESListFolderContinueError *routeError, DBRequestError *networkError) {if (response) {NSArray<DBFILESMetadata *> *entries = response.entries;NSString *cursor = response.cursor;BOOL hasMore = [response.hasMoreboolValue]; [selfprintEntries:entries];if (hasMore) { [selflistFolderContinueWithClient:clientcursor:cursor]; }else {NSLog(@"List folder complete."); } }else {NSLog(@"%@\n%@\n", routeError, networkError); } }];}- (void)printEntries:(NSArray<DBFILESMetadata *> *)entries {for (DBFILESMetadata *entry in entries) {if ([entryisKindOfClass:[DBFILESFileMetadataclass]]) { DBFILESFileMetadata *fileMetadata = (DBFILESFileMetadata *)entry;NSLog(@"File data:%@\n", fileMetadata); }elseif ([entryisKindOfClass:[DBFILESFolderMetadataclass]]) { DBFILESFolderMetadata *folderMetadata = (DBFILESFolderMetadata *)entry;NSLog(@"Folder data:%@\n", folderMetadata); }elseif ([entryisKindOfClass:[DBFILESDeletedMetadataclass]]) { DBFILESDeletedMetadata *deletedMetadata = (DBFILESDeletedMetadata *)entry;NSLog(@"Deleted data:%@\n", deletedMetadata); } }}
-listFolder: and-listFolderContinue:
NSData *fileData = [@"file data example"dataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:NO];// For overriding on uploadDBFILESWriteMode *mode = [[DBFILESWriteModealloc]initWithOverwrite];[[[client.filesRoutesuploadData:@"/test/path/in/Dropbox/account/my_output.txt"mode:modeautorename:@(YES)clientModified:nilmute:@(NO)inputData:fileData]setResponseBlock:^(DBFILESFileMetadata *result, DBFILESUploadError *routeError, DBRequestError *networkError) {if (result) {NSLog(@"%@\n", result); }else {NSLog(@"%@\n%@\n", routeError, networkError); } }]setProgressBlock:^(int64_t bytesUploaded,int64_t totalBytesUploaded,int64_t totalBytesExpectedToUploaded) {NSLog(@"\n%lld\n%lld\n%lld\n", bytesUploaded, totalBytesUploaded, totalBytesExpectedToUploaded);}];
-uploadData:mode:autorename:clientModified:mute:inputData:
Here's an example of an advanced upload case for "batch" uploading a large number of files:
NSMutableDictionary<NSURL *, DBFILESCommitInfo *> *uploadFilesUrlsToCommitInfo = [NSMutableDictionarynew];DBFILESCommitInfo *commitInfo = [[DBFILESCommitInfoalloc]initWithPath:@"/output/path/in/Dropbox/file.txt"];[uploadFilesUrlsToCommitInfosetObject:commitInfoforKey:[NSURLfileURLWithPath:@"/local/path/to/file.txt"]];[client.filesRoutesbatchUploadFiles:uploadFilesUrlsToCommitInfoqueue:nilprogressBlock:^(int64_t uploaded,int64_t uploadedTotal,int64_t expectedToUploadTotal) {NSLog(@"Uploaded:%lld UploadedTotal:%lld ExpectedToUploadTotal:%lld", uploaded, uploadedTotal, expectedToUploadTotal); }responseBlock:^(NSDictionary<NSURL *, DBFILESUploadSessionFinishBatchResultEntry *> *fileUrlsToBatchResultEntries, DBASYNCPollError *finishBatchRouteError, DBRequestError *finishBatchRequestError,NSDictionary<NSURL *, DBRequestError *> *fileUrlsToRequestErrors) {if (fileUrlsToBatchResultEntries) {NSLog(@"Call to `/upload_session/finish_batch/check` succeeded");for (NSURL *clientSideFileUrl in fileUrlsToBatchResultEntries) { DBFILESUploadSessionFinishBatchResultEntry *resultEntry = fileUrlsToBatchResultEntries[clientSideFileUrl];if ([resultEntryisSuccess]) {NSString *dropboxFilePath = resultEntry.success.pathDisplay;NSLog(@"File successfully uploaded from%@ on local machine to%@ in Dropbox.", [clientSideFileUrlpath], dropboxFilePath); }elseif ([resultEntryisFailure]) {// This particular file was not uploaded successfully, although the other// files may have been uploaded successfully. Perhaps implement some retry// logic here based on `uploadNetworkError` or `uploadSessionFinishError` DBRequestError *uploadNetworkError = fileUrlsToRequestErrors[clientSideFileUrl]; DBFILESUploadSessionFinishError *uploadSessionFinishError = resultEntry.failure;// implement appropriate retry logic } } }if (finishBatchRouteError) {NSLog(@"Either bug in SDK code, or transient error on Dropbox server");NSLog(@"%@", finishBatchRouteError); }elseif (finishBatchRequestError) {NSLog(@"Request error from calling `/upload_session/finish_batch/check`");NSLog(@"%@", finishBatchRequestError); }elseif ([fileUrlsToRequestErrorscount] >0) {NSLog(@"Other additional errors (e.g. file doesn't exist client-side, etc.).");NSLog(@"%@", fileUrlsToRequestErrors); } }];
Note: the
batchUploadFiles:route method that is used above automatically chunk-uploads large files, something other upload methods in the SDK donot do. Also, with this route, response and progress handlers are passed directly into the route as arguments, and not via thesetResponseBlockorsetProgressBlockmethods.
-batchUploadFiles:queue:progressBlock:responseBlock:
Here's an example for downloading to a file (NSURL):
NSFileManager *fileManager = [NSFileManagerdefaultManager];NSURL *outputDirectory = [fileManagerURLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask][0];NSURL *outputUrl = [outputDirectoryURLByAppendingPathComponent:@"test_file_output.txt"];[[[client.filesRoutesdownloadUrl:@"/test/path/in/Dropbox/account/my_file.txt"overwrite:YESdestination:outputUrl]setResponseBlock:^(DBFILESFileMetadata *result, DBFILESDownloadError *routeError, DBRequestError *networkError,NSURL *destination) {if (result) {NSLog(@"%@\n", result);NSData *data = [[NSFileManagerdefaultManager]contentsAtPath:[destinationpath]];NSString *dataStr = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];NSLog(@"%@\n", dataStr); }else {NSLog(@"%@\n%@\n", routeError, networkError); } }]setProgressBlock:^(int64_t bytesDownloaded,int64_t totalBytesDownloaded,int64_t totalBytesExpectedToDownload) {NSLog(@"%lld\n%lld\n%lld\n", bytesDownloaded, totalBytesDownloaded, totalBytesExpectedToDownload);}];
-downloadUrl:rev:overwrite:destination:
Here's an example for downloading straight to memory (NSData):
[[[client.filesRoutesdownloadData:@"/test/path/in/Dropbox/account/my_file.txt"]setResponseBlock:^(DBFILESFileMetadata *result, DBFILESDownloadError *routeError, DBRequestError *networkError,NSData *fileContents) {if (result) {NSLog(@"%@\n", result);NSString *dataStr = [[NSStringalloc]initWithData:fileContentsencoding:NSUTF8StringEncoding];NSLog(@"%@\n", dataStr); }else {NSLog(@"%@\n%@\n", routeError, networkError); } }]setProgressBlock:^(int64_t bytesDownloaded,int64_t totalBytesDownloaded,int64_t totalBytesExpectedToDownload) {NSLog(@"%lld\n%lld\n%lld\n", bytesDownloaded, totalBytesDownloaded, totalBytesExpectedToDownload);}];
Currently, the SDK uses a backgroundNSURLSession to perform all download tasks and some upload tasks (including upload from a file, but not from memory or from a stream). Background sessions use a separate process to handle all data transfers. This is conveneient because when your app enters the background, the download / upload will continue.
However, the timeout periods for a backgroundNSURLSession are virtually unlimited, so if you lose your network connection, the error handler will never be executed. Instead, the process will wait for a restored connection, and then resume from there.
If you're looking for more responsive error feedback in the event of a lost connection, you will want to force all requests onto a foregroundNSURLSession. See the example in thenetwork configuration section of the README for how to do this.
To read more, please consult Apple'sdocumentation.
NOTE: You should test all background session behavior onan actual test device andnot the Xcode simulator, which has a lot of buggy behavior when it comes to handling background session behavior.
Dropbox API v2 deals largely with two data types:structs andunions. Broadly speaking, most routearguments are struct types and most routeerrors are union types.
NOTE: In this context, "structs" and "unions" are terms specific to the Dropbox API, and not to any of the languages that are used to query the API, so you should avoid thinking of them in terms of their Objective-C definitions.
Struct types are "traditional" object types, that is, composite types made up of a collection of one or more instance fields. All public instance fields are accessible at runtime, regardless of runtime state.
Union types, on the other hand, represent a single value that can take on multiple value types, depending on state. We capture all of these different type scenarios under one "union object", but that object will exist only as one type at runtime. Each union state type, ortag, may have an associated value (if it doesn't, the union state type is said to bevoid). Associated value types can either be primitives, structs or unions. Although the Objective-C SDK represents union types as objects with multiple instance fields, at most one instance field is accessible at runtime, depending on the tag state of the union.
For example, the/delete endpoint returns an error,DeleteError, which is a union type. TheDeleteError union can take on two different tag states:path_lookup(if there is a problem looking up the path) orpath_write (if there is a problem writing -- or in this case deleting -- to the path). Here, both tag states have non-void associated values (of typesDBFILESLookupError andDBFILESWriteError, respectively).
In this way, one union object is able to capture a multitude of scenarios, each of which has their own value type.
To properly handle union types, you should call each of theis<TAG_STATE> methods associated with the union. Once you have determined the current tag state of the union, you can then safely access the value associated with that tag state (provided there exists an associated value type, i.e., it's notvoid).If at run time you attempt to access a union instance field that is not associated with the current tag state,an exception will be thrown. See below:
[[client.filesRoutesdelete_:@"/test/path/in/Dropbox/account"]setResponseBlock:^(DBFILESMetadata *result, DBFILESDeleteError *routeError, DBRequestError *networkError) {if (result) {NSLog(@"%@\n", result); }else {// Error is with the route specifically (status code 409)if (routeError) {if ([routeErrorisPathLookup]) {// Can safely access this field DBFILESLookupError *pathLookup = routeError.pathLookup;NSLog(@"%@\n", pathLookup); }elseif ([routeErrorisPathWrite]) { DBFILESWriteError *pathWrite = routeError.pathWrite;NSLog(@"%@\n", pathWrite);// This would cause a runtime error// DBFILESLookupError *pathLookup = routeError.pathLookup; } }NSLog(@"%@\n%@\n", routeError, networkError); } }];
In the case of a network error, regardless of whether the error is specific to the route, a genericDBRequestError type will always be returned, which includes information like Dropbox request ID and HTTP status code.
TheDBRequestError type is a special union type which is similar to the standard API v2 union type, but also includes a collection ofas<TAG_STATE> methods, each of which returns a new instance of a particular error subtype.As with accessing associated values in regular unions, theas<TAG_STATE> should only be called after the correspondingis<TAG_STATE> method returns true. See below:
[[client.filesRoutesdelete_:@"/test/path/in/Dropbox/account"]setResponseBlock:^(DBFILESMetadata *result, DBFILESDeleteError *routeError, DBRequestError *networkError) {if (result) {NSLog(@"%@\n", result); }else {if (routeError) {// see handling above }// Error not specific to the route (status codes 500, 400, 401, 403, 404, 429)else {if ([networkErrorisInternalServerError]) { DBRequestInternalServerError *internalServerError = [networkErrorasInternalServerError];NSLog(@"%@\n", internalServerError); }elseif ([networkErrorisBadInputError]) { DBRequestBadInputError *badInputError = [networkErrorasBadInputError];NSLog(@"%@\n", badInputError); }elseif ([networkErrorisAuthError]) { DBRequestAuthError *authError = [networkErrorasAuthError];NSLog(@"%@\n", authError); }elseif ([networkErrorisAccessError]) { DBRequestAccessError *accessError = [networkErrorasAccessError];NSLog(@"%@\n", accessError); }elseif ([networkErrorisRateLimitError]) { DBRequestRateLimitError *rateLimitError = [networkErrorasRateLimitError];NSLog(@"%@\n", rateLimitError); }elseif ([networkErrorisHttpError]) { DBRequestHttpError *genericHttpError = [networkErrorasHttpError];NSLog(@"%@\n", genericHttpError); }elseif ([networkErrorisClientError]) { DBRequestClientError *genericLocalError = [networkErrorasClientError];NSLog(@"%@\n", genericLocalError); } } } }];
Some routes return union types as result types, so you should be prepared to handle these results in the same way that you handle union route errors. Please consult thedocumentationfor each endpoint that you use to ensure you are properly handling the route's response type.
A few routes return result types that aredatatypes with subtypes, that is, structs that can take on multiple state types like unions.
For example, the/delete endpoint returns a genericMetadata type, which can exist either as aFileMetadata struct, aFolderMetadata struct, or aDeletedMetadata struct.To determine at runtime which subtype theMetadata type exists as, perform anisKindOfClass check for each possible class, and then cast the result accordingly. See below:
[[client.filesRoutesdelete_:@"/test/path/in/Dropbox/account"]setResponseBlock:^(DBFILESMetadata *result, DBFILESDeleteError *routeError, DBRequestError *networkError) {if (result) {if ([resultisKindOfClass:[DBFILESFileMetadataclass]]) { DBFILESFileMetadata *fileMetadata = (DBFILESFileMetadata *)result;NSLog(@"File data:%@\n", fileMetadata); }elseif ([resultisKindOfClass:[DBFILESFolderMetadataclass]]) { DBFILESFolderMetadata *folderMetadata = (DBFILESFolderMetadata *)result;NSLog(@"Folder data:%@\n", folderMetadata); }elseif ([resultisKindOfClass:[DBFILESDeletedMetadataclass]]) { DBFILESDeletedMetadata *deletedMetadata = (DBFILESDeletedMetadata *)result;NSLog(@"Deleted data:%@\n", deletedMetadata); } }else {if (routeError) {// see handling above }else {// see handling above } } }];
ThisMetadata object is known as adatatype with subtypes in our API v2 documentation.
Datatypes with subtypes are a way combining structs and unions. Datatypes with subtypes are struct objects that contain a tag, which specifies which subtype the object exists as at runtime. The reason we have this construct, as with unions, is so we can capture a multitude of scenarios with one object.
In the above example, theMetadata type can exists asFileMetadata,FolderMetadata orDeleteMetadata. Each of these types have common instances fields like "name" (the name for the file, folder or deleted type), but also instance fields that are specific to the particular subtype. In order to leverage inheritance, we set a common supertype calledMetadata which captures all of the common instance fields, but also has a tag instance field, which specifies which subtype the object currently exists as.
In this way, datatypes with subtypes are a hybrid of structs and unions. Only a few routes return result types like this.
Normally, errors are handled on a request-by-request basis by callingsetResponseBlock on the returned request task object. Sometimes, however, it makes more sense to handle errors consistently, based on error type, regardless of the source of the request. For instance, maybe you want to display the same dialog every time there is a/files/list_folder error. Or perhaps every time there is an HTTP auth error, you simply want to log the user out of your application.
To implement these examples, you should have code in your app's setup logic (probably in your app delegate) that looks something like the following:
void (^listFolderGlobalResponseBlock)(DBFILESListFolderError *, DBRequestError *, DBTask *) = ^(DBFILESListFolderError *folderError, DBRequestError *networkError, DBTask *restartTask) {if (folderError) {// Display some dialog relating to this error } };void (^networkGlobalResponseBlock)(DBRequestError *, DBTask *) = ^(DBRequestError *networkError, DBTask *restartTask) {if ([networkErrorisAuthError]) {// log the user out of the app, for instance [DBClientsManagerunlinkAndResetClients]; }elseif ([networkErrorisRateLimitError]) {// automatically retry after backoff period DBRequestRateLimitError *rateLimitError = [networkErrorasRateLimitError];int backOff = [rateLimitError.retryAfterintValue];dispatch_after(dispatch_time(DISPATCH_TIME_NOW, backOff * NSEC_PER_SEC),dispatch_get_main_queue(), ^{ [restartTaskrestart]; }); } };// one response block per error type to globally handle[DBGlobalErrorResponseHandlerregisterRouteErrorResponseBlock:listFolderGlobalResponseBlockrouteErrorType:[DBFILESListFolderErrorclass]];// only one response block total to handle all network errors[DBGlobalErrorResponseHandlerregisterNetworkErrorResponseBlock:networkGlobalResponseBlock];
The SDK allows you to set one response block to handle all generic network errors that aren't route-specific (like an HTTP auth error, or a rate-limit error). The SDK also allows you to set a response block to be executed in the event that a certain error type is returned.
These global response blocks will automatically be executedin addition to the response block that you supply for the specific request.
It is possible to configure the networking client used by the SDK to make API requests. You can supply custom fields like a custom user agent or custom delegate queue to manage response handler code.
For instance, you can force the SDK to make all network requests on a foreground session:
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>DBTransportDefaultConfig *transportConfig = [[DBTransportDefaultConfigalloc]initWithAppKey:@"<APP_KEY>"forceForegroundSession:YES];[DBClientsManagersetupWithTransportConfig:transportConfig];
#import<ObjectiveDropboxOfficial/ObjectiveDropboxOfficial.h>DBTransportDefaultConfig *transportConfig = [[DBTransportDefaultConfigalloc]initWithAppKey:@"<APP_KEY>"forceForegroundSession:YES];[DBClientsManagersetupWithTransportConfigDesktop:transportConfig];
See theDBTransportDefaultConfig class for all of the different customizable networking parameters.
By default, response/progress handler code runs on the main thread. You can set a custom response queue for each API call that you make via thesetResponseBlock method, in the event want your response/progress handler code to run on a different thread:
[[client.filesRouteslistFolder:@""]setResponseBlock:^(DBFILESListFolderResult *result, DBFILESListFolderError *routeError, DBRequestError *networkError) {if (result) {NSLog(@"%@", [NSThreadcurrentThread]);// Output: <NSThread: 0x600000261480>{number = 5, name = (null)}NSLog(@"%@", [NSThreadmainThread]);// Output: <NSThread: 0x618000062bc0>{number = 1, name = (null)}NSLog(@"%@\n", result); } }queue:[NSOperationQueuenew]]
The Objective-C SDK includes a convenience class,DBClientsManager, for integrating the different functions of the SDK into one class.
For most apps, it is reasonable to assume that only one Dropbox account (and access token) needs to be managed at a time. In this case, theDBClientsManager flow looks like this:
- call
setupWithAppKey/setupWithAppKeyDesktop(orsetupWithTeamAppKey/setupWithTeamAppKeyDesktop) in integrating app's app delegate DBClientsManagerclass determines whether any access tokens are stored -- if any exist, one token is arbitrarily chosen to use for theauthorizedClient/authorizedTeamClientshared instance- if no token is found, client of the SDK should call
authorizeFromController/authorizeFromControllerDesktopto initiate the OAuth flow - if auth flow is initiated, client of the SDK should call
handleRedirectURL(orhandleRedirectURLTeam) in integrating app's app delegate to handle auth redirect back into the app and store the retrieved access token DBClientsManagerclass sets up aDBUserClient(orDBTeamClient) with the particular network configuration as defined by theDBTransportDefaultConfiginstance passed in (or a standard configuration, if no config instance was passed when thesetupWith...method was called)
TheDBUserClient (orDBTeamClient) is then used to make all of the desired API calls.
- call
unlinkAndResetClientsto logout Dropbox user and clear all access tokens
For some apps, it is necessary to manage more than one Dropbox account (and access token) at a time. In this case, theDBClientsManager flow looks like this:
- access token uids are managed by the app that is integrating with the SDK for later lookup
- call
setupWithAppKey/setupWithAppKeyDesktop(orsetupWithTeamAppKey/setupWithTeamAppKeyDesktop) in integrating app's app delegate DBClientsManagerclass determines whether any access tokens are stored -- if any exist, one token is arbitrarily chosen to use for theauthorizedClient/authorizedTeamClientshared instanceDBClientsManagerclass also populatesauthorizedClients/authorizedTeamClientsshared dictionary from all tokens stored in keychain, if any exist- if no token is found, client of the SDK should call
authorizeFromController/authorizeFromControllerDesktopto initiate the OAuth flow - if auth flow is initiated, call
handleRedirectURL(orhandleRedirectURLTeam) in integrating app's app delegate to handle auth redirect back into the app and store the retrieved access token - at this point, the app that is integrating with the SDK should persistently save the
tokenUidfrom theDBAccessTokenfield of theDBOAuthResultobject returned from thehandleRedirectURL(orhandleRedirectURLTeam) method DBClientsManagerclass sets up aDBUserClient(orDBTeamClient) with the particular network configuration as defined by theDBTransportDefaultConfiginstance passed in (or a standard configuration, if no config instance was passed when thesetupWith...method was called) and saves it to the list of authorized clients
TheDBUserClients (orDBTeamClients) inauthorizedClients /authorizedTeamClients is then used to make all of the desired API calls.
- call
unlinkAndResetClientto logout a particular Dropbox user and clear their access token - call
unlinkAndResetClientsto logout all Dropbox users and clear all access tokens
Example projects that demonstrate how to integrate your app with the SDK can be found in theExamples/ folder.
- DBRoulette - Play a fun game of photo roulette with the image files in your Dropbox!
This section contains relevant info for migrating your app from API v1 to API v2 (which should be finished by June 28, 2017, when API v1 will be retired).
For a general API v1 migration guide, please seehere.
If your app was originally using an earlier API v1 SDK, including theiOS Core SDK, theOS X Core SDK, theiOS Sync SDK, or theOS X Sync SDK, then you can use the v2 SDK to perform a one-time migration of OAuth 1 tokens to OAuth 2.0 tokens, which are used by API v2. That way, when you migrate your app from the earlier SDK to the new API v2 SDK, users will not need to reauthenticate with Dropbox after you perform this update.
To perform this auth token migration, in your app delegate, you should call the following method:
+checkAndPerformV1TokenMigration:queue:appKey:appSecret:
BOOL willPerformMigration = [DBClientsManagercheckAndPerformV1TokenMigration:^(BOOL shouldRetry,BOOL invalidAppKeyOrSecret,NSArray<NSArray<NSString *> *> *unsuccessfullyMigratedTokenData) {if (invalidAppKeyOrSecret) {// Developers should ensure that the appropriate app key and secret are being supplied.// If your app has multiple app keys / secrets, then run this migration method for// each app key / secret combination, and ignore this boolean. }if (shouldRetry) {// Store this BOOL somewhere to retry when network connection has returned }if ([unsuccessfullyMigratedTokenDatacount] !=0) {NSLog(@"The following tokens were unsucessfully migrated:");for (NSArray<NSString *> *tokenData in unsuccessfullyMigratedTokenData) {NSLog(@"DropboxUserID:%@, AccessToken:%@, AccessTokenSecret:%@, StoredAppKey:%@", tokenData[0], tokenData[1], tokenData[2], tokenData[3]); } }if (!invalidAppKeyOrSecret && !shouldRetry && [unsuccessfullyMigratedTokenDatacount] ==0) { [DBClientsManagersetupWithAppKey:@"<APP_KEY>"]; }}queue:nilappKey:@"<APP_KEY>"appSecret:@"<APP_SECRET>"];if (!willPerformMigration) { [DBClientsManagersetupWithAppKey:@"<APP_KEY>"];}
This method should successfully migrate all access tokens stored by the official Dropbox API SDKs from approximately 2012 until present, for both iOS and OS X. It will make one call to our OAuth 1 conversion endpoint for each OAuth 1 token that has been stored in your application's keychain by the v1 SDK. The method will execute all network requests off the main thread.
Here, token migration is treated as an atomic operation. Either all tokens that are possible to migrate are migrated at once, or none of them are. If all token conversion requests complete successfully, then theshouldRetry argument inresponseBlock will beNO. If some token conversion requests succeed and some fail, and if the failures are for any reason other than network connectivity issues (e.g. token has been invalidated), then the migration will continue normally, and those tokens that were unsuccessfully migrated will be skipped, andshouldRetry will beNO. If any of the failures were because of network connectivity issues, none of the tokens will be migrated, andshouldRetry will beYES.
All of our routes and data types are auto-generated using a framework calledStone.
Thestone repo contains all of the Objective-C specific generation logic, and thespec repo contains the language-neutral API endpoint specifications which serveas input to the language-specific generators.
If you're interested in modifying the SDK codebase, you should take the following steps:
- clone this GitHub repository to your local filesystem
- run
git submodule initand thengit submodule update - navigate to
TestObjectiveDropboxand runpod install - open
TestObjectiveDropbox/TestObjectiveDropbox.xcworkspacein Xcode - implement your changes to the SDK source code.
To ensure your changes have not broken any existing functionality, you can run a series of integration tests byfollowing the instructions listed in theViewController.m file.
If you're interested in manually generating the SDK serialization logic, perform the following:
- clone this GitHub repository to your local filesystem
- run
git submodule initand thengit submodule update - navigate to theStone GitHub repo, and install all necessary dependencies
- run
./generate_base_client.pyto generate code
To ensure your changes have not broken any existing functionality, you can run a series of integration tests byfollowing the instructions listed in theViewController.m file.
Please post any bugs to theissue tracker found on the project's GitHub page.
Please include the following with your issue:
- a description of what is not working right
- sample code to help replicate the issue
Thank you!
About
Official Objective-C SDK for the Dropbox API v2.
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Languages
- Objective-C99.8%
- Other0.2%


