### Install CocoaPods Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Use this command to install the CocoaPods dependency manager. Ensure you have Ruby installed. ```bash $ gem install cocoapods ``` -------------------------------- ### Install Carthage Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Install the Carthage dependency manager using Homebrew. Carthage version 0.37.0 or higher is recommended for XCFramework support. ```bash brew update brew install carthage ``` -------------------------------- ### Install CocoaPods Dependency Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Run this command in your project directory after creating or updating your Podfile to install the SDK. Ensure your Xcode project is closed before running. ```bash $ pod install ``` -------------------------------- ### List Folder Contents in Dropbox Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md This example shows how to list the contents of a folder. For large folders, it includes logic to call `listFolderContinue:` to fetch all entries. ```objective-c [[client.filesRoutes listFolder:@"/test/path/in/Dropbox/account"] setResponseBlock:^(DBFILESListFolderResult *response, DBFILESListFolderError *routeError, DBRequestError *networkError) { if (response) { NSArray *entries = response.entries; NSString *cursor = response.cursor; BOOL hasMore = [response.hasMore boolValue]; [self printEntries:entries]; if (hasMore) { NSLog(@"Folder is large enough where we need to call `listFolderContinue:`"); [self listFolderContinueWithClient:client cursor:cursor]; } else { NSLog(@"List folder complete."); } } else { NSLog(@"%@\n%@\n", routeError, networkError); } }]; ``` -------------------------------- ### Configure LSApplicationQueriesSchemes in .plist Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Add these schemes to your application's .plist file to allow the SDK to check for the official Dropbox iOS app installation. ```xml LSApplicationQueriesSchemes dbapi-8-emm dbapi-2 ``` -------------------------------- ### Get Temporary Download Link Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Generates a temporary URL for streaming or downloading a file. The link is valid for 4 hours. ```objective-c #import - (void)getTemporaryLink { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes getTemporaryLink:@"/videos/presentation.mp4"] setResponseBlock:^(DBFILESGetTemporaryLinkResult *result, DBFILESGetTemporaryLinkError *routeError, DBRequestError *networkError) { if (result) { NSLog(@"Temporary link (valid for 4 hours): %@", result.link); NSLog(@"File metadata: %@", result.metadata.name); // Use this link to stream content or download externally NSURL *streamURL = [NSURL URLWithString:result.link]; } }]; } ``` -------------------------------- ### Get Temporary Download Link Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Generates a temporary, time-limited download link for a file, suitable for streaming or external downloads. ```APIDOC ## POST /files/get_temporary_link ### Description Generate a temporary download link for streaming content. ### Method POST ### Endpoint /files/get_temporary_link ### Parameters #### Request Body - **path** (string) - Required - The path to the file you want to get a temporary link for. ### Request Example ```objective-c // Assuming dbUserClient is an authorized DBUserClient instance [[dbUserClient.filesRoutes getTemporaryLink:@"/videos/presentation.mp4"] setResponseBlock:^(DBFILESGetTemporaryLinkResult *result, DBFILESGetTemporaryLinkError *routeError, DBRequestError *networkError) { if (result) { NSLog(@"Temporary link (valid for 4 hours): %@", result.link); NSLog(@"File metadata: %@", result.metadata.name); NSURL *streamURL = [NSURL URLWithString:result.link]; } }]; ``` ### Response #### Success Response (200) - **link** (string) - The temporary download link. - **metadata** (FileMetadata) - Metadata about the file. #### Response Example ```json { "link": "https://dl.dropboxusercontent.com/...", "metadata": { "name": "presentation.mp4", "id": "id:xxxxxxxxxx", "client_modified": "2023-01-01T12:00:00Z", "server_modified": "2023-01-01T12:05:00Z", "rev": "abcdef123456789", "size": 12345678, "path_lower": "/videos/presentation.mp4", "path_display": "/videos/presentation.mp4", "sharing_info": { ... }, "property_groups": { ... }, "has_explicit_shared_members": false } } ``` ``` -------------------------------- ### Implement global error handling Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Register global response blocks for specific route errors and generic network errors in your app's setup logic. ```objective-c 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 ([networkError isAuthError]) { // log the user out of the app, for instance [DBClientsManager unlinkAndResetClients]; } else if ([networkError isRateLimitError]) { // automatically retry after backoff period DBRequestRateLimitError *rateLimitError = [networkError asRateLimitError]; int backOff = [rateLimitError.retryAfter intValue]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, backOff * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [restartTask restart]; }); } }; // one response block per error type to globally handle [DBGlobalErrorResponseHandler registerRouteErrorResponseBlock:listFolderGlobalResponseBlock routeErrorType:[DBFILESListFolderError class]]; // only one response block total to handle all network errors [DBGlobalErrorResponseHandler registerNetworkErrorResponseBlock:networkGlobalResponseBlock]; ``` -------------------------------- ### Search Files in Dropbox Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Performs a search for files and folders. Includes examples for basic search, advanced search with filtering options, and handling pagination via cursors. ```objective-c #import - (void)searchFiles { DBUserClient *client = [DBClientsManager authorizedClient]; // Basic search [[client.filesRoutes searchV2:@"vacation photos"] setResponseBlock:^(DBFILESSearchV2Result *result, DBFILESSearchError *routeError, DBRequestError *networkError) { if (result) { NSLog(@"Found %lu matches", (unsigned long)result.matches.count); for (DBFILESSearchMatchV2 *match in result.matches) { if ([match.metadata isMetadata]) { DBFILESMetadata *metadata = match.metadata.metadata; NSLog(@"Match: %@", metadata.pathDisplay); } } // Handle pagination if (result.hasMore && result.cursor) { [self searchContinueWithCursor:result.cursor]; } } }]; } // Advanced search with options - (void)advancedSearch { DBUserClient *client = [DBClientsManager authorizedClient]; DBFILESSearchOptions *options = [[DBFILESSearchOptions alloc] initWithPath:@"/Documents" maxResults:@(50) orderBy:nil fileStatus:nil filenameOnly:@(NO) fileExtensions:@[@"pdf", @"doc", @"docx"] fileCategories:nil]; [[client.filesRoutes searchV2:@"report" options:options matchFieldOptions:nil includeHighlights:@(YES)] setResponseBlock:^(DBFILESSearchV2Result *result, DBFILESSearchError *routeError, DBRequestError *networkError) { if (result) { for (DBFILESSearchMatchV2 *match in result.matches) { NSLog(@"Found: %@", match.metadata.metadata.pathDisplay); } } }]; } - (void)searchContinueWithCursor:(NSString *)cursor { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes searchContinueV2:cursor] setResponseBlock:^(DBFILESSearchV2Result *result, DBFILESSearchError *routeError, DBRequestError *networkError) { if (result) { for (DBFILESSearchMatchV2 *match in result.matches) { NSLog(@"More matches: %@", match.metadata.metadata.pathDisplay); } } }]; } ``` -------------------------------- ### Setup Global Error Handling in Objective-C Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Register global handlers for network and route-specific errors. The network handler manages authentication, rate limiting, and server/client errors. The route handler targets specific error types like path errors. ```Objective-C #import - (void)setupGlobalErrorHandling { // Handle all network errors globally void (^networkErrorHandler)(DBRequestError *, DBTask *) = ^(DBRequestError *networkError, DBTask *restartTask) { if ([networkError isAuthError]) { NSLog(@"Authentication error - logging out user"); [DBClientsManager unlinkAndResetClients]; // Navigate to login screen } else if ([networkError isRateLimitError]) { DBRequestRateLimitError *rateLimitError = [networkError asRateLimitError]; int backoffSeconds = [rateLimitError.retryAfter intValue]; NSLog(@"Rate limited. Retrying in %d seconds", backoffSeconds); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, backoffSeconds * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [restartTask restart]; }); } else if ([networkError isInternalServerError]) { NSLog(@"Server error - please try again later"); } else if ([networkError isClientError]) { DBRequestClientError *clientError = [networkError asClientError]; NSLog(@"Client error: %@", clientError.nsError.localizedDescription); } }; [DBGlobalErrorResponseHandler registerNetworkErrorResponseBlock:networkErrorHandler]; // Handle specific route errors (e.g., list folder errors) void (^listFolderErrorHandler)(DBFILESListFolderError *, DBRequestError *, DBTask *) = ^(DBFILESListFolderError *folderError, DBRequestError *networkError, DBTask *restartTask) { if (folderError && [folderError isPath]) { NSLog(@"Path error when listing folder: %@", folderError.path); } }; [DBGlobalErrorResponseHandler registerRouteErrorResponseBlock:listFolderErrorHandler routeErrorType:[DBFILESListFolderError class]]; } ``` -------------------------------- ### Initialize DBUserClient on iOS Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Call this method in your application's didFinishLaunchingWithOptions to set up the Dropbox client with your app key. Ensure you have imported ObjectiveDropboxOfficial. ```objective-c #import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [DBClientsManager setupWithAppKey:@""]; return YES; } ``` -------------------------------- ### Initialize DBUserClient on macOS Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Call this method in your application's applicationDidFinishLaunching to set up the Dropbox client for desktop applications. Ensure you have imported ObjectiveDropboxOfficial. ```objective-c #import - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { [DBClientsManager setupWithAppKeyDesktop:@""]; } ``` -------------------------------- ### Initialize Dropbox Client with Access Token Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Create a `DBUserClient` instance by providing a manually retrieved OAuth 2.0 access token. This is an alternative to the programmatic OAuth flow. ```objective-c #import // Initialize with manually retrieved auth token DBUserClient *client = [[DBUserClient alloc] initWithAccessToken:@""]; ``` -------------------------------- ### Initialize Dropbox SDK Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Configure the SDK in the application delegate using the app key or custom transport configuration. ```objective-c #import // iOS App Delegate - didFinishLaunchingWithOptions - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Basic setup with app key only [DBClientsManager setupWithAppKey:@"YOUR_APP_KEY"]; // Or with custom transport configuration for advanced options DBTransportDefaultConfig *transportConfig = [[DBTransportDefaultConfig alloc] initWithAppKey:@"YOUR_APP_KEY" forceForegroundSession:YES]; // Use foreground sessions for quick operations [DBClientsManager setupWithTransportConfig:transportConfig]; return YES; } // macOS App Delegate - applicationDidFinishLaunching - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { [DBClientsManager setupWithAppKeyDesktop:@"YOUR_APP_KEY"]; } ``` -------------------------------- ### Configure network client for platform Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Initialize the network client with custom transport configurations for iOS or macOS. ```objective-c #import DBTransportDefaultConfig *transportConfig = [[DBTransportDefaultConfig alloc] initWithAppKey:@"" forceForegroundSession:YES]; [DBClientsManager setupWithTransportConfig:transportConfig]; ``` ```objective-c #import DBTransportDefaultConfig *transportConfig = [[DBTransportDefaultConfig alloc] initWithAppKey:@"" forceForegroundSession:YES]; [DBClientsManager setupWithTransportConfigDesktop:transportConfig]; ``` -------------------------------- ### Get Authorized Dropbox Client Instance Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Obtain a reference to the `DBUserClient` after a successful programmatic OAuth flow. This client is used for making API requests. ```objective-c #import // Reference after programmatic auth flow DBUserClient *client = [DBClientsManager authorizedClient]; ``` -------------------------------- ### Configure Custom Network Settings Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Initializes the Dropbox client with custom transport configurations, including user agents, additional headers, and forced foreground sessions. ```objective-c #import - (void)setupWithCustomConfig { // Force foreground sessions for responsive error handling DBTransportDefaultConfig *config = [[DBTransportDefaultConfig alloc] initWithAppKey:@"YOUR_APP_KEY" appSecret:nil userAgent:@"MyApp/1.0" asMemberId:nil additionalHeaders:@{@"X-Custom-Header": @"value"} delegateQueue:nil forceForegroundSession:YES sharedContainerIdentifier:nil]; [DBClientsManager setupWithTransportConfig:config]; } ``` -------------------------------- ### Initiate OAuth 2 Flow on macOS Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Uses PKCE to request user scopes and authorize the application via the desktop workspace. ```objective-c #import - (void)myButtonInControllerPressed { // OAuth 2 code flow with PKCE that grants a short-lived token with scopes, and performs refreshes of the token automatically. DBScopeRequest *scopeRequest = [[DBScopeRequest alloc] initWithScopeType:DBScopeTypeUser scopes:@[@"account_info.read"] includeGrantedScopes:NO]; [DBClientsManager authorizeFromControllerDesktopV2:[NSWorkspace sharedWorkspace] controller:self loadingStatusDelegate:nil openURL:^(NSURL *url) { [[NSWorkspace sharedWorkspace] openURL:url]; } scopeRequest:scopeRequest]; } ``` -------------------------------- ### Carthage Update macOS Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Run this command to checkout and build the Dropbox Objective-C SDK for macOS using Carthage. Ensure you use the --use-xcframeworks flag. ```bash carthage update --platform Mac --use-xcframeworks ``` -------------------------------- ### Carthage Update iOS Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Run this command to checkout and build the Dropbox Objective-C SDK for iOS using Carthage. Ensure you use the --use-xcframeworks flag. ```bash carthage update --platform iOS --use-xcframeworks ``` -------------------------------- ### Begin iOS Authorization Flow Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Initiate the OAuth 2.0 code flow with PKCE to obtain a short-lived token. This method handles authentication via the official Dropbox app or Safari View Controller and automatically refreshes the token. ```objective-c #import - (void)myButtonInControllerPressed { // OAuth 2 code flow with PKCE that grants a short-lived token with scopes, and performs refreshes of the token automatically. DBScopeRequest *scopeRequest = [[DBScopeRequest alloc] initWithScopeType:DBScopeTypeUser scopes:@["account_info.read"] includeGrantedScopes:NO]; [DBClientsManager authorizeFromControllerV2:[UIApplication sharedApplication] controller:[[self class] topMostController] loadingStatusDelegate:nil openURL:^(NSURL *url) { [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil]; } scopeRequest:scopeRequest]; } + (UIViewController*)topMostController { UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController; while (topController.presentedViewController) { topController = topController.presentedViewController; } return topController; } ``` -------------------------------- ### Carthage Cartfile Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Add this line to your Cartfile to specify the Dropbox Objective-C SDK as a dependency for Carthage. Use the appropriate version tag. ```text # ObjectiveDropboxOfficial github "https://github.com/dropbox/dropbox-sdk-obj-c" ~> 7.4.1 ``` -------------------------------- ### Create Folders in Dropbox Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Create single or multiple folders using the filesRoutes client. Use autorename to handle naming conflicts automatically. ```objective-c #import - (void)createFolder { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes createFolderV2:@"/new_folder" autorename:@(YES)] setResponseBlock:^(DBFILESCreateFolderResult *result, DBFILESCreateFolderError *routeError, DBRequestError *networkError) { if (result) { NSLog(@"Folder created: %@", result.metadata.pathDisplay); } else if (routeError) { if ([routeError isPath]) { DBFILESWriteError *writeError = routeError.path; if ([writeError isConflict]) { NSLog(@"Folder already exists"); } } } }]; } // Create multiple folders at once - (void)createMultipleFolders { DBUserClient *client = [DBClientsManager authorizedClient]; NSArray *paths = @[@"/batch_folder_1", @"/batch_folder_2", @"/batch_folder_3"]; [[client.filesRoutes createFolderBatch:paths autorename:@(YES) forceAsync:@(NO)] setResponseBlock:^(DBFILESCreateFolderBatchLaunch *result, DBNilObject *routeError, DBRequestError *networkError) { if ([result isComplete]) { for (DBFILESCreateFolderBatchResultEntry *entry in result.complete.entries) { if ([entry isSuccess]) { NSLog(@"Created: %@", entry.success.metadata.pathDisplay); } } } }]; } ``` -------------------------------- ### Configure CFBundleURLTypes in .plist Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Register a unique Dropbox URL scheme in your .plist file for handling redirect completion of the OAuth 2.0 authorization flow. Replace with your actual app key. ```xml CFBundleURLTypes CFBundleURLSchemes db- CFBundleURLName ``` -------------------------------- ### Create a Folder in Dropbox Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Use this snippet to create a new folder in your Dropbox account. It handles the response asynchronously, logging success or error details. ```objective-c [[client.filesRoutes createFolder:@"/test/path/in/Dropbox/account"] setResponseBlock:^(DBFILESFolderMetadata *result, DBFILESCreateFolderError *routeError, DBRequestError *networkError) { if (result) { NSLog(@"%@\n", result); } else { NSLog(@"%@\n%@\n", routeError, networkError); } }]; ``` -------------------------------- ### Continue Listing Folder Contents Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md This method is used to fetch the next page of results when listing a large folder's contents. It recursively calls itself if more pages are available. ```objective-c - (void)listFolderContinueWithClient:(DBUserClient *)client cursor:(NSString *)cursor { [[client.filesRoutes listFolderContinue:cursor] setResponseBlock:^(DBFILESListFolderResult *response, DBFILESListFolderContinueError *routeError, DBRequestError *networkError) { if (response) { NSArray *entries = response.entries; NSString *cursor = response.cursor; BOOL hasMore = [response.hasMore boolValue]; [self printEntries:entries]; if (hasMore) { [self listFolderContinueWithClient:client cursor:cursor]; } else { NSLog(@"List folder complete."); } } else { NSLog(@"%@\n%@\n", routeError, networkError); } }]; } ``` -------------------------------- ### Manually Add Subproject Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Drag the ObjectiveDropboxOfficial.xcodeproj file from the Carthage checkout directory into your Xcode project navigator after running carthage update. ```bash carthage update --platform iOS --use-xcframeworks ``` ```bash carthage update --platform Mac --use-xcframeworks ``` -------------------------------- ### Authenticate with OAuth 2.0 PKCE Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Initiate the OAuth 2.0 authorization flow with specific scopes for iOS and macOS platforms. ```objective-c #import // Start the OAuth flow from a view controller (iOS) - (void)authenticateWithDropbox { // Define the scopes your app needs DBScopeRequest *scopeRequest = [[DBScopeRequest alloc] initWithScopeType:DBScopeTypeUser scopes:@[@"account_info.read", @"files.content.read", @"files.content.write"] includeGrantedScopes:NO]; [DBClientsManager authorizeFromControllerV2:[UIApplication sharedApplication] controller:self loadingStatusDelegate:nil openURL:^(NSURL *url) { [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil]; } scopeRequest:scopeRequest]; } // macOS authentication - (void)authenticateWithDropboxDesktop { DBScopeRequest *scopeRequest = [[DBScopeRequest alloc] initWithScopeType:DBScopeTypeUser scopes:@[@"account_info.read", @"files.content.read"] includeGrantedScopes:NO]; [DBClientsManager authorizeFromControllerDesktopV2:[NSWorkspace sharedWorkspace] controller:self loadingStatusDelegate:nil openURL:^(NSURL *url) { [[NSWorkspace sharedWorkspace] openURL:url]; } scopeRequest:scopeRequest]; } ``` -------------------------------- ### Batch Upload Files with Dropbox SDK for Objective-C Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md The `batchUploadFiles` method is designed for uploading a large number of files efficiently. It automatically chunks large files and allows for detailed progress tracking and error handling for each file during the batch upload process. ```objective-c NSMutableDictionary *uploadFilesUrlsToCommitInfo = [NSMutableDictionary new]; DBFILESCommitInfo *commitInfo = [[DBFILESCommitInfo alloc] initWithPath:@"/output/path/in/Dropbox/file.txt"]; [uploadFilesUrlsToCommitInfo setObject:commitInfo forKey:[NSURL fileURLWithPath:@"/local/path/to/file.txt"]]; [client.filesRoutes batchUploadFiles:uploadFilesUrlsToCommitInfo queue:nil progressBlock:^(int64_t uploaded, int64_t uploadedTotal, int64_t expectedToUploadTotal) { NSLog(@"Uploaded: %lld UploadedTotal: %lld ExpectedToUploadTotal: %lld", uploaded, uploadedTotal, expectedToUploadTotal); } responseBlock:^(NSDictionary *fileUrlsToBatchResultEntries, DBASYNCPollError *finishBatchRouteError, DBRequestError *finishBatchRequestError, NSDictionary *fileUrlsToRequestErrors) { if (fileUrlsToBatchResultEntries) { NSLog(@"Call to `/upload_session/finish_batch/check` succeeded"); for (NSURL *clientSideFileUrl in fileUrlsToBatchResultEntries) { DBFILESUploadSessionFinishBatchResultEntry *resultEntry = fileUrlsToBatchResultEntries[clientSideFileUrl]; if ([resultEntry isSuccess]) { NSString *dropboxFilePath = resultEntry.success.pathDisplay; NSLog(@"File successfully uploaded from %@ on local machine to %@ in Dropbox.", [clientSideFileUrl path], dropboxFilePath); } else if ([resultEntry isFailure]) { // 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); } else if (finishBatchRequestError) { NSLog(@"Request error from calling `/upload_session/finish_batch/check`"); NSLog(@"%@", finishBatchRequestError); } else if ([fileUrlsToRequestErrors count] > 0) { NSLog(@"Other additional errors (e.g. file doesn't exist client-side, etc.)."); NSLog(@"%@", fileUrlsToRequestErrors); } }]; ``` -------------------------------- ### Execute API Calls on Custom Queue Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Demonstrates running Dropbox API requests on a background NSOperationQueue and dispatching UI updates back to the main thread. ```objective-c // Run API calls on a custom queue - (void)runOnCustomQueue { DBUserClient *client = [DBClientsManager authorizedClient]; NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init]; backgroundQueue.name = @"com.myapp.dropbox.background"; [[client.filesRoutes listFolder:@""] setResponseBlock:^(DBFILESListFolderResult *result, DBFILESListFolderError *routeError, DBRequestError *networkError) { // This block runs on backgroundQueue NSLog(@"Current thread: %@", [NSThread currentThread]); // Switch to main thread for UI updates dispatch_async(dispatch_get_main_queue(), ^{ // Update UI here }); } queue:backgroundQueue]; } ``` -------------------------------- ### CocoaPods macOS Podfile Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Add this to your Podfile to integrate the ObjectiveDropboxOfficial SDK for macOS. Ensure your platform version and project name are correctly specified. ```ruby platform :osx, '10.10' use_frameworks! target '' do pod 'ObjectiveDropboxOfficial' end ``` -------------------------------- ### List Folder Contents in Objective-C Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Retrieves folder contents and handles pagination using a cursor for large directories. ```objective-c #import - (void)listFolderContents { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes listFolder:@""] // Empty string for root folder setResponseBlock:^(DBFILESListFolderResult *result, DBFILESListFolderError *routeError, DBRequestError *networkError) { if (result) { NSLog(@"Found %lu entries", (unsigned long)result.entries.count); for (DBFILESMetadata *entry in result.entries) { if ([entry isKindOfClass:[DBFILESFileMetadata class]]) { DBFILESFileMetadata *file = (DBFILESFileMetadata *)entry; NSLog(@"File: %@ (size: %@ bytes)", file.name, file.size); } else if ([entry isKindOfClass:[DBFILESFolderMetadata class]]) { DBFILESFolderMetadata *folder = (DBFILESFolderMetadata *)entry; NSLog(@"Folder: %@", folder.name); } } // Handle pagination for large folders if ([result.hasMore boolValue]) { [self listFolderContinueWithCursor:result.cursor]; } } else if (routeError) { if ([routeError isPath]) { NSLog(@"Path error: %@", routeError.path); } } else if (networkError) { NSLog(@"Network error: %@", networkError); } }]; } - (void)listFolderContinueWithCursor:(NSString *)cursor { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes listFolderContinue:cursor] setResponseBlock:^(DBFILESListFolderResult *result, DBFILESListFolderContinueError *routeError, DBRequestError *networkError) { if (result) { for (DBFILESMetadata *entry in result.entries) { NSLog(@"Entry: %@", entry.name); } if ([result.hasMore boolValue]) { [self listFolderContinueWithCursor:result.cursor]; } } }]; } ``` -------------------------------- ### Print Metadata Entries Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md A helper method to iterate through and log metadata for files, folders, and deleted items within a directory listing. ```objective-c - (void)printEntries:(NSArray *)entries { for (DBFILESMetadata *entry in entries) { if ([entry isKindOfClass:[DBFILESFileMetadata class]]) { DBFILESFileMetadata *fileMetadata = (DBFILESFileMetadata *)entry; NSLog(@"File data: %@\n", fileMetadata); } else if ([entry isKindOfClass:[DBFILESFolderMetadata class]]) { DBFILESFolderMetadata *folderMetadata = (DBFILESFolderMetadata *)entry; NSLog(@"Folder data: %@\n", folderMetadata); } else if ([entry isKindOfClass:[DBFILESDeletedMetadata class]]) { DBFILESDeletedMetadata *deletedMetadata = (DBFILESDeletedMetadata *)entry; NSLog(@"Deleted data: %@\n", deletedMetadata); } } } ``` -------------------------------- ### CocoaPods iOS Podfile Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Add this to your Podfile to integrate the ObjectiveDropboxOfficial SDK for iOS. Ensure your platform version and project name are correctly specified. ```ruby platform :ios, '9.0' use_frameworks! target '' do pod 'ObjectiveDropboxOfficial' end ``` -------------------------------- ### Migrate Dropbox OAuth 1 Tokens to OAuth 2.0 Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Call this method in your app delegate to migrate OAuth 1 tokens from earlier SDKs to OAuth 2.0. It handles token conversion and provides feedback on success or failure. Ensure correct app key and secret are provided. If migration fails due to network issues, it indicates a retry is needed. ```objective-c BOOL willPerformMigration = [DBClientsManager checkAndPerformV1TokenMigration:^(BOOL shouldRetry, BOOL invalidAppKeyOrSecret, NSArray *> *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 ([unsuccessfullyMigratedTokenData count] != 0) { NSLog(@"The following tokens were unsucessfully migrated:"); for (NSArray *tokenData in unsuccessfullyMigratedTokenData) { NSLog(@"DropboxUserID: %@, AccessToken: %@, AccessTokenSecret: %@, StoredAppKey: %@", tokenData[0], tokenData[1], tokenData[2], tokenData[3]); } } if (!invalidAppKeyOrSecret && !shouldRetry && [unsuccessfullyMigratedTokenData count] == 0) { [DBClientsManager setupWithAppKey:@""]; } } queue:nil appKey:@"" appSecret:@""]; if (!willPerformMigration) { [DBClientsManager setupWithAppKey:@""]; } ``` -------------------------------- ### Move and Copy Files in Dropbox Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Methods for relocating or duplicating files and folders, including batch processing for multiple items. ```objective-c #import // Move a file or folder - (void)moveItem { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes moveV2:@"/source/file.txt" toPath:@"/destination/file.txt" allowSharedFolder:nil autorename:@(YES) allowOwnershipTransfer:nil] setResponseBlock:^(DBFILESRelocationResult *result, DBFILESRelocationError *routeError, DBRequestError *networkError) { if (result) { NSLog(@"Moved to: %@", result.metadata.pathDisplay); } else if (routeError) { if ([routeError isFromLookup]) { NSLog(@"Source not found"); } else if ([routeError isTo]) { NSLog(@"Destination error: %@", routeError.to); } } }]; } // Copy a file or folder - (void)copyItem { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes dCopyV2:@"/original/document.pdf" toPath:@"/copies/document_copy.pdf"] setResponseBlock:^(DBFILESRelocationResult *result, DBFILESRelocationError *routeError, DBRequestError *networkError) { if (result) { NSLog(@"Copied to: %@", result.metadata.pathDisplay); } }]; } // Batch move multiple items - (void)batchMoveItems { DBUserClient *client = [DBClientsManager authorizedClient]; NSArray *entries = @[ [[DBFILESRelocationPath alloc] initWithFromPath:@"/old/file1.txt" toPath:@"/new/file1.txt"], [[DBFILESRelocationPath alloc] initWithFromPath:@"/old/file2.txt" toPath:@"/new/file2.txt"] ]; [[client.filesRoutes moveBatchV2:entries autorename:@(YES) allowOwnershipTransfer:nil] setResponseBlock:^(DBFILESRelocationBatchV2Launch *result, DBNilObject *routeError, DBRequestError *networkError) { if ([result isComplete]) { for (DBFILESRelocationBatchResultEntry *entry in result.complete.entries) { if ([entry isSuccess]) { NSLog(@"Moved: %@", entry.success.metadata.pathDisplay); } } } }]; } ``` -------------------------------- ### Download File to Local Path Source: https://github.com/dropbox/dropbox-sdk-obj-c/blob/master/README.md Downloads a file from Dropbox to a specified local NSURL destination. ```objective-c NSFileManager *fileManager = [NSFileManager defaultManager]; NSURL *outputDirectory = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0]; NSURL *outputUrl = [outputDirectory URLByAppendingPathComponent:@"test_file_output.txt"]; [[[client.filesRoutes downloadUrl:@"/test/path/in/Dropbox/account/my_file.txt" overwrite:YES destination:outputUrl] setResponseBlock:^(DBFILESFileMetadata *result, DBFILESDownloadError *routeError, DBRequestError *networkError, NSURL *destination) { if (result) { NSLog(@"%@\n", result); NSData *data = [[NSFileManager defaultManager] contentsAtPath:[destination path]]; NSString *dataStr = [[NSString alloc] initWithData:data encoding: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); }]; ``` -------------------------------- ### Monitor Folder Changes with Longpoll Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Uses a cursor-based approach to monitor folder changes, waiting for updates and fetching them when detected. ```objective-c #import - (void)monitorFolderChanges { DBUserClient *client = [DBClientsManager authorizedClient]; // First, get a cursor for the folder [[client.filesRoutes listFolderGetLatestCursor:@"/sync_folder" recursive:@(YES) includeMediaInfo:@(NO) includeDeleted:@(YES) includeHasExplicitSharedMembers:@(NO) includeMountedFolders:@(YES) limit:nil sharedLink:nil includePropertyGroups:nil includeNonDownloadableFiles:@(YES)] setResponseBlock:^(DBFILESListFolderGetLatestCursorResult *result, DBFILESListFolderError *routeError, DBRequestError *networkError) { if (result) { [self longpollWithCursor:result.cursor]; } }]; } - (void)longpollWithCursor:(NSString *)cursor { DBUserClient *client = [DBClientsManager authorizedClient]; // Longpoll waits up to 30 seconds (configurable up to 480 seconds) for changes [[client.filesRoutes listFolderLongpoll:cursor timeout:@(30)] setResponseBlock:^(DBFILESListFolderLongpollResult *result, DBFILESListFolderLongpollError *routeError, DBRequestError *networkError) { if (result) { if ([result.changes boolValue]) { NSLog(@"Changes detected! Fetching updates..."); [self fetchChangesWithCursor:cursor]; } else { NSLog(@"No changes, polling again..."); // Continue polling with the same cursor [self longpollWithCursor:cursor]; } } }]; } - (void)fetchChangesWithCursor:(NSString *)cursor { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes listFolderContinue:cursor] setResponseBlock:^(DBFILESListFolderResult *result, DBFILESListFolderContinueError *routeError, DBRequestError *networkError) { if (result) { for (DBFILESMetadata *entry in result.entries) { if ([entry isKindOfClass:[DBFILESDeletedMetadata class]]) { NSLog(@"Deleted: %@", entry.pathDisplay); } else { NSLog(@"Changed: %@", entry.pathDisplay); } } // Continue polling with the new cursor [self longpollWithCursor:result.cursor]; } }]; } ``` -------------------------------- ### Batch Upload Large Files Objective-C Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Use batch upload for uploading multiple large files efficiently with automatic chunking. Requires preparing a dictionary of file URLs and commit information. ```Objective-C #import - (void)batchUploadFiles { DBUserClient *client = [DBClientsManager authorizedClient]; // Prepare files to upload NSMutableDictionary *uploadFilesUrlsToCommitInfo = [NSMutableDictionary new]; // Add first file NSURL *file1URL = [NSURL fileURLWithPath:@"/path/to/local/file1.txt"]; DBFILESCommitInfo *commitInfo1 = [[DBFILESCommitInfo alloc] initWithPath:@"/uploads/file1.txt"]; uploadFilesUrlsToCommitInfo[file1URL] = commitInfo1; // Add second file NSURL *file2URL = [NSURL fileURLWithPath:@"/path/to/local/file2.txt"]; DBFILESCommitInfo *commitInfo2 = [[DBFILESCommitInfo alloc] initWithPath:@"/uploads/file2.txt"]; uploadFilesUrlsToCommitInfo[file2URL] = commitInfo2; // Start batch upload [client.filesRoutes batchUploadFiles:uploadFilesUrlsToCommitInfo queue:nil progressBlock:^(int64_t uploaded, int64_t uploadedTotal, int64_t expectedToUploadTotal) { float progress = (float)uploadedTotal / expectedToUploadTotal; NSLog(@"Batch upload progress: %.2f%%", progress * 100); } responseBlock:^(NSDictionary *fileUrlsToBatchResultEntries, DBASYNCPollError *finishBatchRouteError, DBRequestError *finishBatchRequestError, NSDictionary *fileUrlsToRequestErrors) { if (fileUrlsToBatchResultEntries) { for (NSURL *fileUrl in fileUrlsToBatchResultEntries) { DBFILESUploadSessionFinishBatchResultEntry *resultEntry = fileUrlsToBatchResultEntries[fileUrl]; if ([resultEntry isSuccess]) { NSLog(@"Uploaded %@ to %@", fileUrl.lastPathComponent, resultEntry.success.pathDisplay); } else if ([resultEntry isFailure]) { NSLog(@"Failed to upload %@: %@", fileUrl.lastPathComponent, resultEntry.failure); } } } if (finishBatchRouteError) { NSLog(@"Batch error: %@", finishBatchRouteError); } }]; } ``` -------------------------------- ### Retrieve File Metadata Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Fetches metadata for a specific file or folder, including optional media information for photos and videos. ```objective-c #import - (void)getFileMetadata { DBUserClient *client = [DBClientsManager authorizedClient]; [[client.filesRoutes getMetadata:@"/photos/vacation.jpg" includeMediaInfo:@(YES) includeDeleted:@(NO) includeHasExplicitSharedMembers:@(YES) includePropertyGroups:nil] setResponseBlock:^(DBFILESMetadata *result, DBFILESGetMetadataError *routeError, DBRequestError *networkError) { if (result) { if ([result isKindOfClass:[DBFILESFileMetadata class]]) { DBFILESFileMetadata *file = (DBFILESFileMetadata *)result; NSLog(@"File: %@", file.name); NSLog(@"Size: %@ bytes", file.size); NSLog(@"Modified: %@", file.clientModified); NSLog(@"Rev: %@", file.rev); NSLog(@"Content Hash: %@", file.contentHash); // Media info for photos/videos if (file.mediaInfo && [file.mediaInfo isMetadata]) { DBFILESMediaMetadata *mediaMetadata = file.mediaInfo.metadata; if ([mediaMetadata isKindOfClass:[DBFILESPhotoMetadata class]]) { DBFILESPhotoMetadata *photo = (DBFILESPhotoMetadata *)mediaMetadata; NSLog(@"Photo dimensions: %@ x %@", photo.dimensions.width, photo.dimensions.height); } } } else if ([result isKindOfClass:[DBFILESFolderMetadata class]]) { DBFILESFolderMetadata *folder = (DBFILESFolderMetadata *)result; NSLog(@"Folder: %@", folder.name); } } }]; } ``` -------------------------------- ### Download File to URL Objective-C Source: https://context7.com/dropbox/dropbox-sdk-obj-c/llms.txt Downloads a file from Dropbox to a specified local file URL. Handles progress updates and provides detailed error handling for path-related issues. ```Objective-C #import // Download to file URL - (void)downloadFileToURL { DBUserClient *client = [DBClientsManager authorizedClient]; NSURL *outputDirectory = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0]; NSURL *outputURL = [outputDirectory URLByAppendingPathComponent:@"downloaded_file.txt"]; [[[client.filesRoutes downloadUrl:@"/test/hello.txt" overwrite:YES destination:outputURL] setResponseBlock:^(DBFILESFileMetadata *result, DBFILESDownloadError *routeError, DBRequestError *networkError, NSURL *destination) { if (result) { NSLog(@"Downloaded: %@", result.name); NSLog(@"Saved to: %@", destination.path); NSLog(@"Size: %@ bytes", result.size); // Read the downloaded content NSData *data = [NSData dataWithContentsOfURL:destination]; NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Content: %@", content); } else if (routeError) { if ([routeError isPath]) { DBFILESLookupError *pathError = routeError.path; if ([pathError isNotFound]) { NSLog(@"File not found"); } } } }] setProgressBlock:^(int64_t bytesDownloaded, int64_t totalBytesDownloaded, int64_t totalBytesExpectedToDownload) { float progress = (float)totalBytesDownloaded / totalBytesExpectedToDownload; NSLog(@"Download progress: %.2f%%", progress * 100); }]; } ```