### Configuration Guide Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/MANIFEST.txt Guide for configuring SDK components, including network and session settings. ```APIDOC ## Configuration Guide ### Description Details the configuration options for SDK components, focusing on network settings, session management, and transport layer setup. ### Key Areas - `NetworkSessionConfiguration`: Reference for network configuration. - SDK components setup. ### Usage - Examples for configuring network and session settings are available in `quick-reference.md`. ``` -------------------------------- ### Setup Dropbox OAuth Flow Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/README.md Guides through setting up the OAuth manager, initiating the authorization flow, handling redirect URLs, and checking for an authorized client. ```swift // 1. Create OAuth manager let oauthManager = DropboxOAuthManager(appKey: "your_app_key", secureStorageAccess: keychain) DropboxOAuthManager.sharedOAuthManager = oauthManager // 2. Start auth flow oauthManager.authorizeFromSharedApplication(UIApplication.shared.delegate!) // 3. Handle redirect func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { return DropboxClientsManager.handleRedirectURL(url, includeBackgroundClient: true) { result in switch result { case .success: print("Authenticated!") case .error(let err, _): print("Error: \(err)") case .cancel: print("Cancelled") case nil: break } } } // 4. Use client if let client = DropboxClientsManager.authorizedClient { client.files.listFolder(path: "") { result, error in // Use result } } ``` -------------------------------- ### Basic Dropbox Client Setup Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/NetworkSessionConfiguration.md Initialize a Dropbox client using the default network session configuration. ```swift // Use defaults for most cases let config = NetworkSessionConfiguration.default let client = DropboxClient(accessToken: token, sessionConfiguration: config) ``` -------------------------------- ### Initialize DropboxClient with Access Token Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Basic setup for a Dropbox client using a provided access token. ```swift let client = DropboxClient(accessToken: "sl.B...") ``` -------------------------------- ### Swift Example for Team Members Info Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Example of how to fetch team member information using Swift with SwiftyDropbox. Requires importing SwiftyDropbox. ```swift import SwiftyDropbox let userSelectArg = Team.UserSelectorArg.email("some@email.com") DropboxClientsManager.team.membersGetInfo(members: [userSelectArg]).response { response, error in if let result = response { // Handle result } else { // Handle error } } ``` -------------------------------- ### Objective-C Example for Team Members Info Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Example of fetching team member information using the Objective-C compatibility layer of SwiftyDropbox. Requires importing SwiftyDropboxObjC. ```objc @import SwiftyDropboxObjC; DBXTeamUserSelectorArgEmail *selector = [[DBXTeamUserSelectorArgEmail alloc] init:@"some@email.com"] [[DBXDropboxClientsManager.authorizedTeamClient.team membersGetInfoWithMembers:@[selector]] responseWithCompletionHandler:^(NSArray * _Nullable result, DBXTeamMembersGetInfoError * _Nullable routeError, DBXCallError * _Nullable error) { if (result) { // Handle result } else { // Handle error } }]; ``` -------------------------------- ### NetworkSessionConfiguration Examples Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/types.md Illustrates how to create and customize NetworkSessionConfiguration objects for different use cases, including standard, ephemeral, and background sessions. ```swift // Standard session let config = NetworkSessionConfiguration(kind: .default) // Ephemeral (no cache) let ephemeral = NetworkSessionConfiguration(kind: .ephemeral) // Background session let background = NetworkSessionConfiguration.background( withIdentifier: "com.example.app.background", sharedContainerIdentifier: "group.com.example.app" ) // Customize var config = NetworkSessionConfiguration.default config.timeoutIntervalForRequest = 30 config.allowsCellularAccess = false ``` -------------------------------- ### Initialize DropboxOAuthManager with Standard Setup Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Standard initialization for DropboxOAuthManager using an app key and secure storage access. ```swift let oauthManager = DropboxOAuthManager( appKey: "your_app_key", secureStorageAccess: keyChainAccess ) DropboxOAuthManager.sharedOAuthManager = oauthManager ``` -------------------------------- ### ShortLivedAccessTokenProvider Example Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/OAuth.md Demonstrates how to create a ShortLivedAccessTokenProvider and use it with DropboxClient. The token is automatically refreshed when needed. ```swift let provider = ShortLivedAccessTokenProvider( token: shortLivedToken, tokenRefresher: oauthManager ) let client = DropboxClient(accessTokenProvider: provider) // Token is automatically refreshed before expiration when needed client.files.listFolder(path: "") { result, error in // Works even if token was refreshed in the background } ``` -------------------------------- ### Install Dependencies with CocoaPods Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Run the 'pod install' command after updating your Podfile to install the specified dependencies. ```bash $ pod install ``` -------------------------------- ### Single User Dropbox Setup and API Call Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClientsManager.md Demonstrates the typical flow for setting up a single Dropbox user, handling redirects, and making an API call. Requires OAuthManager initialization. ```swift // 1. Initialize OAuth manager let oauthManager = DropboxOAuthManager(appKey: "your_app_key", secureStorageAccess: secureStorage) // 2. Start auth flow oauthManager.authorizeFromSharedApplication(sharedApp) // 3. Handle redirect func handleDeeplink(_ url: URL) { DropboxClientsManager.handleRedirectURL(url, includeBackgroundClient: true) { result in if case .success = result { // Client is ready let client = DropboxClientsManager.authorizedClient } } } // 4. Make API calls DropboxClientsManager.authorizedClient?.files.listFolder(path: "") { response, error in if let entries = response?.entries { print("Files: \(entries)") } } // 5. Logout DropboxClientsManager.unlinkClients() ``` -------------------------------- ### OAuth 2.0 and Authentication Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/INDEX.md Comprehensive guide to the OAuth 2.0 flow, token management, and authentication setup using DropboxOAuthManager and related classes. ```APIDOC ## OAuth 2.0 & Authentication ### Description This document details the complete OAuth 2.0 authentication flow, including token management, refresh patterns, and error handling. It covers the necessary classes and protocols for secure user authentication. ### Core Components - `DropboxOAuthManager`: Manages the OAuth flow (7 methods, 2 properties). - `DropboxAccessToken`: Represents an access token (class with init, 4 properties). - `AccessTokenProvider`: Protocol for providing access tokens. - `LongLivedAccessTokenProvider`: Concrete implementation for long-lived tokens. - `ShortLivedAccessTokenProvider`: Concrete implementation for short-lived tokens. - `DropboxOAuthResult`: Enum for OAuth flow outcomes (success, error, cancel). - `OAuth2Error`: Enum detailing 13 specific OAuth2 error codes. - `SharedApplication`: Protocol for interacting with the shared application context. - `AccessTokenRefreshing`: Protocol for handling token refreshes. ### Key Patterns ```swift let oauthManager = DropboxOAuthManager(appKey: "key", secureStorageAccess: keychain) oauthManager.authorizeFromSharedApplication(appDelegate, usePKCE: true) let handled = oauthManager.handleRedirectURL(url) { result in ... } ``` ``` -------------------------------- ### Install CocoaPods Dependency Manager Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Install CocoaPods using the gem command. This is a prerequisite for managing project dependencies. ```bash $ gem install cocoapods ``` -------------------------------- ### Background Task Setup for Downloads Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/Request-Types.md Configures a Dropbox client for background transfers and initiates a download request. This allows downloads to continue even if the app is suspended or terminated. ```swift // Initialize background client let bgConfig = NetworkSessionConfiguration.background(withIdentifier: "com.example.app.bg") let bgClient = DropboxClient(accessToken: token, sessionConfiguration: bgConfig) // Create request and configure for background bgClient.files.download(path: "/large_file.zip", destination: url) .persistingString(string: "important_file") .response { result, error in // Called when download completes (even if app was suspended) } ``` -------------------------------- ### Getting Team Members Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxTeamClient.md Example workflow for retrieving a list of team members and their basic profile information. ```APIDOC ## Typical Workflows ### Getting Team Members ```swift teamClient.team.membersList() { response, error in if let members = response?.members { for member in members { print("Member ID: \(member.profile.accountId)") print("Email: \(member.profile.email)") } } } ``` ``` -------------------------------- ### sdkVersion Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClientsManager.md The installed version of the SwiftyDropbox SDK. This is a read-only property. ```APIDOC ## sdkVersion ### Description The installed version of the SwiftyDropbox SDK. Read-only. ### Property `public static var sdkVersion: String` ``` -------------------------------- ### Refresh Access Token Example Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/OAuth.md Demonstrates how to refresh a short-lived access token. This is useful when the current token is expired or about to expire. Ensure you have the necessary scopes defined. ```swift oauthManager.refreshAccessToken(token, scopes: [], queue: .main) { result in if case .success(let newToken) = result { print("Token refreshed, expires at: \(newToken.tokenExpirationTimestamp ?? 0)") } } ``` -------------------------------- ### Install SwiftyDropbox with Swift Package Manager Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Integrate the Dropbox Swift SDK into your project using Swift Package Manager by adding the repository URL. Refer to Apple's documentation for detailed steps. ```text https://github.com/dropbox/SwiftyDropbox.git ``` -------------------------------- ### Initiate OAuth Flow Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/OAuth.md Start the OAuth authentication process by presenting the Dropbox login page. Supports both legacy and modern PKCE flows, with options to specify requested scopes for PKCE. ```swift // Legacy token flow let appDelegate = UIApplication.shared.delegate as! AppDelegate oauthManager.authorizeFromSharedApplication(appDelegate) ``` ```swift // Modern PKCE flow with specific scopes oauthManager.authorizeFromSharedApplication( appDelegate, usePKCE: true, scopeRequest: ScopeRequest(scopeType: .individual, scopes: ["files.metadata.read"]) ) ``` -------------------------------- ### Initiate Authorization Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/OAuth.md Starts the OAuth authorization process from a view controller by calling authorizeFromSharedApplication on the shared OAuth manager. ```swift // In view controller oauthManager.authorizeFromSharedApplication( UIApplication.shared.delegate as! UIApplicationDelegate ) ``` -------------------------------- ### DropboxOAuthResult Handling Example Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/OAuth.md Provides a function to handle the DropboxOAuthResult, printing messages based on whether authentication succeeded, failed with an error, or was cancelled. ```swift func handleOAuthResult(_ result: DropboxOAuthResult?) { guard let result = result else { return } switch result { case .success(let token): print("User authenticated: \(token.uid)") case .error(let error, let description): switch error { case .accessDenied: print("User denied access") case .invalidGrant: print("Token expired or revoked") default: print("OAuth error: \(error) \(description ?? "")") } case .cancel: print("User cancelled") } } ``` -------------------------------- ### Initiate OAuth 2 Flow on macOS Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Use this function to start the OAuth 2 code flow with PKCE on macOS. It requests user account information read scope and automatically handles token refreshes. ```Swift import SwiftyDropbox func myButtonInControllerPressed() { // OAuth 2 code flow with PKCE that grants a short-lived token with scopes, and performs refreshes of the token automatically. let scopeRequest = ScopeRequest(scopeType: .user, scopes: ["account_info.read"], includeGrantedScopes: false) DropboxClientsManager.authorizeFromControllerV2( sharedApplication: NSApplication.shared, controller: self, loadingStatusDelegate: nil, openURL: {(url: URL) -> Void in NSWorkspace.shared.open(url)}, scopeRequest: scopeRequest ) } ``` -------------------------------- ### Perform File Operations Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/quick-reference.md Examples of common file operations using the Dropbox Swift SDK, including listing directory contents, retrieving file metadata, uploading files with progress tracking, and downloading files to a specified destination or directly into memory. ```swift // List files client.files.listFolder(path: "") { response, error in if let result = response { for entry in result.entries { print(entry.name) } } } // Get metadata client.files.getMetadata(path: "/file.txt") { metadata, error in if let metadata = metadata { print("Size: \(metadata.size)") } } // Upload with progress client.files.upload(path: "/file.txt", input: data) .progress { p in print("Progress: \(p.fractionCompleted)") } .response { metadata, error in if let metadata = metadata { print("Uploaded: \(metadata.id)") } } // Download to file let destination = FileManager.default.documentsDirectory.appendingPathComponent("file.txt") client.files.download(path: "/file.txt", destination: destination) .progress { p in print("Progress: \(p.fractionCompleted)") } .response { result, error in if let (metadata, url) = result { print("Downloaded to: \(url)") } } // Download to memory client.files.download(path: "/file.txt") .response { result, error in if let (metadata, data) = result { let content = String(data: data, encoding: .utf8) print(content ?? "") } } ``` -------------------------------- ### Configure Custom URLCache Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/NetworkSessionConfiguration.md Provide a custom URLCache implementation. Setting to nil uses the system default. Example shows disabling the cache. ```swift public var urlCache: URLCache? { get set } ``` ```swift var config = NetworkSessionConfiguration.default config.urlCache = URLCache(memoryCapacity: 0, diskCapacity: 0) // Disable cache ``` -------------------------------- ### Multi-Session Setup with Custom Timeouts Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Configures multiple network sessions with different timeout intervals for standard and long-polling requests. This allows for optimized network behavior based on request type. ```swift // Standard request session let standardConfig = NetworkSessionConfiguration.default standardConfig.timeoutIntervalForRequest = 30 // Long-polling session (for listFolderLongpoll) let longpollConfig = NetworkSessionConfiguration.default longpollConfig.timeoutIntervalForRequest = 480 // Background session let bgConfig = NetworkSessionConfiguration.background( withIdentifier: "com.example.app.bg" ) let client = DropboxTransportClientImpl( accessToken: token, sessionConfiguration: standardConfig, longpollSessionConfiguration: longpollConfig ) let bgClient = DropboxClient( accessToken: token, sessionConfiguration: bgConfig ) ``` -------------------------------- ### Initiate OAuth 2 Flow on iOS Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Use this function to start the OAuth 2 code flow with PKCE on iOS. It requests user account information read scope and automatically handles token refreshes. ```Swift import SwiftyDropbox func myButtonInControllerPressed() { // OAuth 2 code flow with PKCE that grants a short-lived token with scopes, and performs refreshes of the token automatically. let scopeRequest = ScopeRequest(scopeType: .user, scopes: ["account_info.read"], includeGrantedScopes: false) DropboxClientsManager.authorizeFromControllerV2( UIApplication.shared, controller: self, loadingStatusDelegate: nil, openURL: { (url: URL) -> Void in UIApplication.shared.open(url, options: [:], completionHandler: nil) }, scopeRequest: scopeRequest ) } ``` -------------------------------- ### Configure Plist for LSApplicationQueriesSchemes Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Add LSApplicationQueriesSchemes 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 ``` -------------------------------- ### Access Dropbox API Routes Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Instantiate `DropboxClient` and access various API namespaces like files, users, and sharing directly through the client object. Examples show fetching metadata, user account details, and listing shared links. ```swift let client = DropboxClient(accessToken: token) // Access files namespace client.files.getMetadata(path: "/file.txt") { response, error in if let metadata = response { print("File size: \(metadata.size)") } } // Access users namespace client.users.getCurrentAccount { account, error in if let account = account { print("User: \(account.name.displayName)") } } // Access sharing namespace client.sharing.listSharedLinks { result, error in // Handle shared links } ``` -------------------------------- ### Use Async/Await for API Calls Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/quick-reference.md Demonstrates how to perform Dropbox API calls asynchronously using Swift's async/await syntax, available on iOS 13+ and macOS 10.15+. Shows examples using both `try/await` for direct error handling and `responseResult()` for a `Result` enum-based approach. ```swift // Available on iOS 13+ / macOS 10.15+ @available(iOS 13.0, macOS 10.15, *) async { do { // Using try/await let metadata = try await client.files.getMetadata(path: "/file.txt").response() print("Size: \(metadata.size)") } catch let error as CallError { print("Error: \(error)") } } // Or with Result @available(iOS 13.0, macOS 10.15, *) async { let result = await client.files.listFolder(path: "").responseResult() switch result { case .success(let response): print("Files: \(response.entries.count)") case .failure(let error): print("Error: \(error)") } } ``` -------------------------------- ### Initialize NetworkSessionConfiguration with Different Kinds Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/NetworkSessionConfiguration.md Demonstrates how to create instances of NetworkSessionConfiguration for default, ephemeral, and background sessions. ```swift let defaultSession = NetworkSessionConfiguration(kind: .default) let ephemeralSession = NetworkSessionConfiguration(kind: .ephemeral) let backgroundSession = NetworkSessionConfiguration(kind: .background("com.example.bg")) ``` -------------------------------- ### Create Dropbox Client Instances Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/quick-reference.md Instantiate a Dropbox client for different scenarios, including basic user clients, clients with custom network configurations, background transfer clients, and team clients. Also shows how to create a user client from a team token and use short-lived access tokens. ```swift // Basic user client let client = DropboxClient(accessToken: "sl.B...") // With custom network config let config = NetworkSessionConfiguration.default let client = DropboxClient(accessToken: token, sessionConfiguration: config) // For background transfers let bgConfig = NetworkSessionConfiguration.background(withIdentifier: "com.example.app.bg") let bgClient = DropboxClient(accessToken: token, sessionConfiguration: bgConfig) // Team client let teamClient = DropboxTeamClient(accessToken: teamToken) // User client from team token let userClient = teamClient.asMember("dbid:AAH4dL...") // With short-lived token let provider = ShortLivedAccessTokenProvider(token: token, tokenRefresher: oauthManager) let client = DropboxClient(accessTokenProvider: provider) ``` -------------------------------- ### Initialize Dropbox Client on iOS Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Set up the SwiftyDropbox SDK with your app key in the application delegate for iOS. This is required before making API calls. ```swift import SwiftyDropbox func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { DropboxClientsManager.setupWithAppKey("") return true } ``` -------------------------------- ### Initialize Dropbox Client on macOS Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Set up the SwiftyDropbox SDK with your app key in the application delegate for macOS. This is required before making API calls. ```swift import SwiftyDropbox func applicationDidFinishLaunching(_ aNotification: Notification) { DropboxClientsManager.setupWithAppKeyDesktop("") } ``` -------------------------------- ### Initializing DropboxTeamClient Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxTeamClient.md Demonstrates different ways to initialize the DropboxTeamClient using static access tokens, access token providers, or existing OAuth managers. ```APIDOC ## Initializers ### Init with Static Access Token ```swift public convenience init(accessToken: String) ``` **Description:** Initializes the client with a static team OAuth 2.0 access token. **Parameters:** - **accessToken** (String) - Required - Team OAuth 2.0 access token with admin scopes. **Example:** ```swift let teamClient = DropboxTeamClient(accessToken: "sl.B...") ``` ### Init with AccessTokenProvider ```swift public convenience init( accessTokenProvider: AccessTokenProvider, sessionConfiguration: NetworkSessionConfiguration? = nil ) ``` **Description:** Initializes the client with an access token provider that manages the team token lifecycle. **Parameters:** - **accessTokenProvider** (AccessTokenProvider) - Required - Access token provider managing team token lifecycle. - **sessionConfiguration** (NetworkSessionConfiguration?) - Optional - Custom network session configuration. **Example:** ```swift let provider = ShortLivedAccessTokenProvider(token: teamToken, tokenRefresher: oauthManager) let teamClient = DropboxTeamClient(accessTokenProvider: provider) ``` ### Init with DropboxAccessToken and OAuth Manager ```swift public convenience init( accessToken: DropboxAccessToken, dropboxOauthManager: DropboxOAuthManager, sessionConfiguration: NetworkSessionConfiguration? = nil ) ``` **Description:** Initializes the client using a DropboxAccessToken and an OAuth manager for token handling. **Parameters:** - **accessToken** (DropboxAccessToken) - Required - Team token (long or short-lived). - **dropboxOauthManager** (DropboxOAuthManager) - Required - OAuth manager for token handling. - **sessionConfiguration** (NetworkSessionConfiguration?) - Optional - Custom network configuration. **Example:** ```swift let teamClient = DropboxTeamClient( accessToken: teamToken, dropboxOauthManager: oauthManager ) ``` ### Designated Initializer ```swift public init(transportClient: DropboxTransportClient) ``` **Description:** The designated initializer, typically used internally with a pre-configured transport client. **Parameters:** - **transportClient** (DropboxTransportClient) - The underlying transport client. Typically created by convenience initializers. **Throws:** `fatalError` if transport client lacks access token provider. ``` -------------------------------- ### Initialize DropboxClient with Custom Network Configuration Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Configure a Dropbox client with a custom network session configuration, such as an ephemeral session. ```swift let config = NetworkSessionConfiguration(kind: .ephemeral) let client = DropboxClient( accessToken: token, sessionConfiguration: config ) ``` -------------------------------- ### Set Up OAuth 2.0 Authorization Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/quick-reference.md Configure the OAuth manager for app authentication, initiate the authorization flow, and handle the redirect URL to obtain an access token. Demonstrates how to check for an authorized client and log out. ```swift // Create manager let oauthManager = DropboxOAuthManager(appKey: "app_key", secureStorageAccess: keychain) DropboxOAuthManager.sharedOAuthManager = oauthManager // Start auth oauthManager.authorizeFromSharedApplication(UIApplication.shared.delegate!) // Handle redirect (in AppDelegate or SceneDelegate) DropboxClientsManager.handleRedirectURL(url, includeBackgroundClient: true) { result in switch result { case .success(let token): print("Authenticated: \(token.uid)") case .error(let error, let description): print("Error: \(error)") case .cancel: print("Cancelled") case nil: break } } // Use client if let client = DropboxClientsManager.authorizedClient { // Make API calls } // Logout DropboxClientsManager.unlinkClients() ``` -------------------------------- ### Accessing the Authorized Client Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClientsManager.md Get the primary authorized user client. This property is set after successful OAuth authentication and is nil when the user is unlinked. ```swift if let client = DropboxClientsManager.authorizedClient { client.files.listFolder(path: "") { response, error in // Handle response } } ``` -------------------------------- ### Initialize DropboxTransportClient with Full Configuration Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Provides comprehensive control over client initialization, including access tokens, base hosts, user agents, and various session configurations. ```swift public convenience init( accessToken: String, baseHosts: BaseHosts = .default, userAgent: String? = nil, selectUser: String? = nil, sessionConfiguration: NetworkSessionConfiguration = .default, longpollSessionConfiguration: NetworkSessionConfiguration = .defaultLongpoll, filesAccess: FilesAccess = FilesAccessImpl(), authChallengeHandler: AuthChallenge.Handler? = nil, pathRoot: Common.PathRoot? = nil, headersForRouteHost: HeadersForRouteRequest? = nil ) ``` ```swift let client = DropboxTransportClientImpl( accessToken: token, baseHosts: .default, userAgent: "MyApp/1.0", selectUser: "team_member_id", sessionConfiguration: bgConfig, authChallengeHandler: certPinningHandler, pathRoot: .home ) ``` -------------------------------- ### Cocoapods Setup for Objective-C Compatibility Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md To use the Objective-C compatibility layer with Cocoapods, specify the `SwiftyDropboxObjC` pod in your Podfile. Ensure `use_frameworks!` is enabled. ```ruby use_frameworks! target '' do pod 'SwiftyDropboxObjC', '~> 10.2.4' end ``` -------------------------------- ### Initialize SwiftyDropbox Client Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/README.md Initialize a Dropbox client with an access token. You can also provide a custom network session configuration. ```swift // Basic setup let client = DropboxClient(accessToken: "sl.B...") // Or with custom network config let config = NetworkSessionConfiguration.default let client = DropboxClient(accessToken: token, sessionConfiguration: config) ``` -------------------------------- ### Initialize DropboxTeamClient with DropboxAccessToken and OAuth Manager Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxTeamClient.md Initialize the team client with a DropboxAccessToken and a DropboxOAuthManager. This initializer also accepts an optional custom network session configuration. ```swift let teamClient = DropboxTeamClient( accessToken: teamToken, dropboxOauthManager: oauthManager ) ``` -------------------------------- ### Create NetworkSessionConfiguration Instances Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Instantiate NetworkSessionConfiguration with different kinds: default, ephemeral, or background. The background kind requires a unique identifier for the session. ```swift let defaultConfig = NetworkSessionConfiguration(kind: .default) let ephemeralConfig = NetworkSessionConfiguration(kind: .ephemeral) let bgConfig = NetworkSessionConfiguration(kind: .background("com.example.app.bg")) ``` -------------------------------- ### Initialize Background Networking Client Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Create a background client by providing a background session identifier. For shared containers, specify that as well. ```Swift import SwiftyDropbox DropboxClientsManager.setupWithAppKey( "", backgroundSessionIdentifier: "", requestsToReconnect: { requestResults in // app code to handle results of completed requests } ) ``` ```Swift DropboxClientsManager.setupWithAppKey( "", backgroundSessionIdentifier: "" sharedContainerIdentifier: "", requestsToReconnect: { requestResults in // app code to handle results of completed requests } ) ``` -------------------------------- ### Get Authorized Dropbox Client Instance Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Obtain a reference to the authorized Dropbox client. Use this for making subsequent API calls after a successful authentication flow. ```Swift import SwiftyDropbox // Reference after programmatic auth flow let client = DropboxClientsManager.authorizedClient ``` ```Swift import SwiftyDropbox // Initialize with manually retrieved auth token let client = DropboxClient(accessToken: "") ``` -------------------------------- ### Initialize DropboxOAuthManager and Authorize Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/INDEX.md Initialize DropboxOAuthManager with an app key and keychain access, then initiate the OAuth authorization flow using PKCE. ```swift let oauthManager = DropboxOAuthManager(appKey: "key", secureStorageAccess: keychain) ouathManager.authorizeFromSharedApplication(appDelegate, usePKCE: true) ``` -------------------------------- ### Retrieve All Background Requests Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Call `getAllRequests` to get an array of `Result` objects, each representing a background task. This is crucial for reconnecting incomplete background requests during app lifecycle events. ```swift client.getAllRequests { results in for result in results { switch result { case .success(let request): // Reconnect the request print("Reconnect: \(request)") case .failure(let error): print("Failed to reconnect: \(error)") } } } ``` -------------------------------- ### Get Team Members List Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxTeamClient.md Retrieve a list of all team members using the 'team.membersList()' method. This provides access to each member's profile information, including account ID and email. ```swift teamClient.team.membersList() { response, error in if let members = response?.members { for member in members { print("Member ID: \(member.profile.accountId)") print("Email: \(member.profile.email)") } } } ``` -------------------------------- ### Initialize DropboxClient with Team Member Selection Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Initialize a Dropbox client for a specific team member using their ID and an access token. ```swift let client = DropboxClient( accessToken: teamToken, selectUser: "team_member_id" ) ``` -------------------------------- ### Initialize DropboxClient with DropboxAccessToken and OAuth Manager Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Construct a client using a DropboxAccessToken object and an associated DropboxOAuthManager. This method handles the creation of an appropriate token provider internally. ```swift public convenience init( accessToken: DropboxAccessToken, dropboxOauthManager: DropboxOAuthManager, sessionConfiguration: NetworkSessionConfiguration? = nil ) ``` ```swift let client = DropboxClient(accessToken: token, dropboxOauthManager: oauthManager) ``` -------------------------------- ### Initialize DropboxOAuthManager with Custom Host Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Initialize DropboxOAuthManager with a custom host, typically for Dropbox Business accounts. ```swift let oauthManager = DropboxOAuthManager( appKey: "app_key", host: "custom.dropboxbusiness.com", secureStorageAccess: keyChainAccess ) ``` -------------------------------- ### Get User-Scoped Client for a Team Member Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxTeamClient.md Create a user-scoped DropboxClient from a team client to make API calls on behalf of a specific team member. This is useful for admin operations requiring user-scoped file access. ```swift let teamClient = DropboxTeamClient(accessToken: teamToken) // Get a user client for a specific team member let userClient = teamClient.asMember("dbid:AAH4dL...") // Now make user-scoped calls userClient.files.listFolder(path: "") { response, error in if let result = response { print("User's files: \(result.entries)") } } ``` -------------------------------- ### Create DropboxClient with Path Root Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Use `withPathRoot` to create a new `DropboxClient` instance with a different path root context. This is useful for switching between home and team namespaces. ```swift let homeClient = client.withPathRoot(.home) let teamClient = client.withPathRoot(.root("team_namespace_id")) ``` -------------------------------- ### Initialize DropboxTeamClient with Static Access Token Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxTeamClient.md Initialize the team client using a static OAuth 2.0 access token. Ensure the token has the necessary admin scopes. ```swift let teamClient = DropboxTeamClient(accessToken: "sl.B...") ``` -------------------------------- ### Batch Get Metadata for Multiple Paths Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/quick-reference.md Efficiently retrieve metadata for multiple files or folders by iterating through a list of paths and making individual `getMetadata` calls. Errors for individual paths are printed but do not stop the batch operation. ```swift func batchGetMetadata(paths: [String]) async throws -> [Files.Metadata] { var results: [Files.Metadata] = [] for path in paths { do { let metadata = try await client.files.getMetadata(path: path).response() results.append(metadata) } catch { print("Error getting \(path): \(error)") } } return results } ``` -------------------------------- ### Initialize DropboxClient with Background Session Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/configuration.md Set up a Dropbox client to use a background session for network requests, identified by a specific identifier and shared container. ```swift let bgConfig = NetworkSessionConfiguration.background( withIdentifier: "com.example.app.background", sharedContainerIdentifier: "group.com.example.app" ) let bgClient = DropboxClient( accessToken: token, sessionConfiguration: bgConfig ) ``` -------------------------------- ### Initialize DropboxClient with AccessTokenProvider Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Initialize the client using an AccessTokenProvider for managing short-lived tokens that require refreshing. Supports optional delegated access and custom network configurations. ```swift public convenience init( accessTokenProvider: AccessTokenProvider, selectUser: String? = nil, sessionConfiguration: NetworkSessionConfiguration? = nil, pathRoot: Common.PathRoot? = nil ) ``` ```swift let tokenProvider = ShortLivedAccessTokenProvider(token: accessToken, tokenRefresher: oauthManager) let client = DropboxClient(accessTokenProvider: tokenProvider) ``` -------------------------------- ### Handle Dropbox API Errors Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Route methods on `DropboxClient` return errors that can be handled using a switch statement. This example demonstrates how to differentiate between various error types like authentication, access, route, HTTP, and client errors. ```swift client.files.getMetadata(path: "/file.txt") { response, error in if let error = error { switch error { case .authError(let authError, _, _, _): print("Auth failed: \(authError)") case .accessError(let accessError, _, _, _): print("Access denied: \(accessError)") case .routeError(let boxedError, _, _, _): print("Route error: \(boxedError.unboxed)") case .httpError(let code, _, _): print("HTTP error: \(code ?? -1)") case .clientError(let clientError): print("Client error: \(clientError)") default: print("Other error: \(error)") } } } ``` -------------------------------- ### Delegated User Access Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxTeamClient.md Demonstrates how to get a list of team members and then create user-scoped clients to perform operations on behalf of individual members. This is useful for building administrative tools or applications that need to interact with data across the team. ```APIDOC ## Delegated User Access ### Description This operation allows you to retrieve a list of all members within a Dropbox team. Once you have the list of members, you can create individual, user-scoped clients for each member using their account ID. These user-scoped clients enable you to perform operations as if you were that specific member, such as listing their files. ### Method `teamClient.team.membersList()` followed by `teamClient.asMember(memberId)` ### Parameters - `teamClient`: An instance of `DropboxTeamClient` authenticated with team admin scopes. - `memberId` (string): The unique account ID of the team member for whom to create a user-scoped client. ### Code Example ```swift // Get list of team members teamClient.team.membersList { membersResponse, error in guard let members = membersResponse?.members else { return } // Create user-scoped clients for specific members for member in members { let userClient = teamClient.asMember(member.profile.accountId) // Perform user-scoped operations userClient.files.listFolder(path: "") { filesResponse, error in if let entries = filesResponse?.entries { print("Member \(member.profile.email) has \(entries.count) items") } } } } ``` ``` -------------------------------- ### Initializer for ShortLivedAccessTokenProvider Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/OAuth.md Initializes the ShortLivedAccessTokenProvider with a token and a token refresher. ```APIDOC ## Initializer ShortLivedAccessTokenProvider ### Description Initializes the ShortLivedAccessTokenProvider with a token and a token refresher. ### Parameters #### Path Parameters * **token** (DropboxAccessToken) - Required - The initial short-lived token. * **tokenRefresher** (AccessTokenRefreshing) - Required - Object that refreshes the token (e.g., DropboxOAuthManager). ### Request Example ```swift let provider = ShortLivedAccessTokenProvider( token: shortLivedToken, tokenRefresher: oauthManager ) let client = DropboxClient(accessTokenProvider: provider) // Token is automatically refreshed before expiration when needed client.files.listFolder(path: "") { result, error in // Works even if token was refreshed in the background } ``` ``` -------------------------------- ### Initialize DropboxOAuthManager Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/OAuth.md Configure the OAuth manager with your app key and a secure storage handler. This instance will manage the authentication process. ```swift let oauthManager = DropboxOAuthManager( appKey: "your_app_key", secureStorageAccess: secureStorage ) DropboxOAuthManager.sharedOAuthManager = oauthManager ``` ```swift let oauthManager = DropboxOAuthManager( appKey: "app_key", host: "custom.dropboxbusiness.com", secureStorageAccess: secureStorage ) ``` -------------------------------- ### Migrating dropbox-sdk-obj-c: Create Folder V2 Source: https://github.com/dropbox/swiftydropbox/blob/master/README.md Compares the method for creating a folder using the older dropbox-sdk-obj-c with the SwiftyDropbox Objective-C layer. Note the changes in method names and response handlers. ```objc [[[DBClientsManager authorizedClient].filesRoutes createFolderV2:@"/some/folder/path"] setResponseBlock:^(DBFILESCreateFolderResult * _Nullable result, DBFILESCreateFolderError * _Nullable routeError, DBRequestError * _Nullable networkError) { // Handle response }]; ``` ```objc [[DBXDropboxClientsManager.authorizedClient.files createFolderV2WithPath:@"some/folder/path"] responseWithCompletionHandler:^(DBXFilesCreateFolderResult * _Nullable result, DBXFilesCreateFolderError * _Nullable routeError, DBXCallError * _Nullable error) { // Handle response }]; ``` -------------------------------- ### Handle Dropbox API Errors Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/quick-reference.md Illustrates comprehensive error handling for Dropbox API calls. The example shows how to inspect the `error` object to differentiate between various error types such as authentication errors, access errors, route-specific errors, rate limiting, client errors, HTTP errors, and serialization issues. ```swift client.files.getMetadata(path: "/file.txt").response { metadata, error in if let error = error { // Check error type switch error { case .authError(let authErr, _, _, _): print("Auth failed: \(authErr)") case .accessError(let accessErr, _, _, _): print("Access denied: \(accessErr)") case .routeError(let box, _, _, _): // Type-cast route-specific error if let metadataError = box.unboxed as? Files.GetMetadataError { print("Route error: \(metadataError)") } case .rateLimitError(let rateErr, _, _, _): let retryAfter = rateErr.retryAfter print("Rate limited. Retry after: \(retryAfter)s") case .clientError(let clientErr): print("Client error: \(clientErr)") case .httpError(let code, let message, _): print("HTTP error: \(code ?? 0)") case .serializationError(let err): print("Parse error: \(err)") default: print("Other error: \(error)") } } } ``` -------------------------------- ### List Team Members and Access Individual Member Files Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/quick-reference.md Demonstrates how to list all members of a Dropbox team and then obtain a client specific to a team member to list their files. ```swift // List team members teamClient.team.membersList() { response, error in if let members = response?.members { for member in members { print("Member: \(member.profile.email)") } } } // Get user client for team member let memberId = "dbid:AAH4dL..." let userClient = teamClient.asMember(memberId) // List that member's files userClient.files.listFolder(path: "") { response, error in if let entries = response?.entries { print("Files: \(entries)") } } ``` -------------------------------- ### NetworkSessionConfiguration Initializers Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/types.md Initializers for creating NetworkSessionConfiguration instances. Use the standard initializer for kind-based configuration or the static method for background sessions. ```swift public init(kind: Kind) ``` ```swift public static func background( withIdentifier identifier: String, sharedContainerIdentifier: String? = nil ) -> Self ``` -------------------------------- ### Init with DropboxAccessToken and OAuth Manager Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Initializes a DropboxClient with a DropboxAccessToken and an OAuthManager, allowing the manager to handle token creation and provide an appropriate token provider. ```APIDOC ## Init with DropboxAccessToken and OAuth Manager ### Description Initializes a DropboxClient with a DropboxAccessToken and an OAuthManager, allowing the manager to handle token creation and provide an appropriate token provider. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Initializer Signature ```swift public convenience init( accessToken: DropboxAccessToken, dropboxOauthManager: DropboxOAuthManager, sessionConfiguration: NetworkSessionConfiguration? = nil ) ``` ### Parameters - **accessToken** (DropboxAccessToken) - Required - A DropboxAccessToken object (long or short-lived). The manager creates an appropriate token provider. - **dropboxOauthManager** (DropboxOAuthManager) - Required - The OAuth manager for creating and managing token providers. - **sessionConfiguration** (NetworkSessionConfiguration?) - Optional - Custom network configuration. ### Example ```swift let client = DropboxClient(accessToken: token, dropboxOauthManager: oauthManager) ``` ``` -------------------------------- ### Init with AccessTokenProvider Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Initializes a DropboxClient using an AccessTokenProvider, which is ideal for managing short-lived tokens that require refreshing. It also supports delegated access and custom network configurations. ```APIDOC ## Init with AccessTokenProvider ### Description Initializes a DropboxClient using an AccessTokenProvider, which is ideal for managing short-lived tokens that require refreshing. It also supports delegated access and custom network configurations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Initializer Signature ```swift public convenience init( accessTokenProvider: AccessTokenProvider, selectUser: String? = nil, sessionConfiguration: NetworkSessionConfiguration? = nil, pathRoot: Common.PathRoot? = nil ) ``` ### Parameters - **accessTokenProvider** (AccessTokenProvider) - Required - An access token provider that manages token lifecycle. Use for short-lived tokens that need refresh. - **selectUser** (String?) - Optional - The user ID of a team member for delegated access. - **sessionConfiguration** (NetworkSessionConfiguration?) - Optional - Custom network configuration. - **pathRoot** (Common.PathRoot?) - Optional - The path root context for API calls. ### Example ```swift let tokenProvider = ShortLivedAccessTokenProvider(token: accessToken, tokenRefresher: oauthManager) let client = DropboxClient(accessTokenProvider: tokenProvider) ``` ``` -------------------------------- ### Background Task Client and Download Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/quick-reference.md Configure a background session for downloads that can continue even if the app is suspended. Handle completion in the AppDelegate. ```swift let bgConfig = NetworkSessionConfiguration.background( withIdentifier: "com.example.app.background", sharedContainerIdentifier: "group.com.example.app" ) let bgClient = DropboxClient(accessToken: token, sessionConfiguration: bgConfig) bgClient.files.download(path: "/file.zip", destination: url) .persistingString(string: "download_id_123") .response { result, error in if let (metadata, location) = result { print("Downloaded to: \(location)") } } ``` ```swift func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { DropboxClientsManager.handleEventsForBackgroundURLSession( with: identifier, creationInfos: [], completionHandler: completionHandler ) { requests in for result in requests { switch result { case .success(let request): print("Reconnect: \(request)") case .failure(let error): print("Error: \(error)") } } } } ``` -------------------------------- ### Initialize DropboxClient with Static Access Token Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Use this initializer for long-lived OAuth 2.0 access tokens. It allows optional specification of a select user for team token holders and custom network session configurations. ```swift public convenience init( accessToken: String, selectUser: String? = nil, sessionConfiguration: NetworkSessionConfiguration? = nil, pathRoot: Common.PathRoot? = nil ) ``` ```swift let client = DropboxClient(accessToken: "sl.B...") ``` -------------------------------- ### Method Chaining for Uploads Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/Request-Types.md Demonstrates chaining multiple methods for an upload request, including persisting a string, tracking progress, and handling the final response. This pattern allows for sequential configuration of requests. ```swift client.files.upload(path: "/file.txt", input: data) .persistingString(string: "upload_id") .progress { p in print("Progress: \(p.fractionCompleted)") } .response { result, error in print(result ?? error!) } ``` -------------------------------- ### Init with Static Access Token Source: https://github.com/dropbox/swiftydropbox/blob/master/_autodocs/api-reference/DropboxClient.md Initializes a DropboxClient with a static OAuth 2.0 access token. This is suitable for long-lived tokens and can optionally specify a user for delegated access or a custom network configuration. ```APIDOC ## Init with Static Access Token ### Description Initializes a DropboxClient with a static OAuth 2.0 access token. This is suitable for long-lived tokens and can optionally specify a user for delegated access or a custom network configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Initializer Signature ```swift public convenience init( accessToken: String, selectUser: String? = nil, sessionConfiguration: NetworkSessionConfiguration? = nil, pathRoot: Common.PathRoot? = nil ) ``` ### Parameters - **accessToken** (String) - Required - The OAuth 2.0 access token string for a user. Use this for long-lived tokens. - **selectUser** (String?) - Optional - The user ID of a team member. When specified, allows the client to make API calls on behalf of this team member. Only for team token holders. - **sessionConfiguration** (NetworkSessionConfiguration?) - Optional - Custom URLSession configuration for network requests. If not provided, uses default configuration. - **pathRoot** (Common.PathRoot?) - Optional - The path root context for the API calls (home, root namespace, or specific namespace ID). ### Example ```swift let client = DropboxClient(accessToken: "sl.B...") ``` ```