The Sync API is like having a private filesystem for your app with its very own Dropbox client running in the background. Your app can read, create, and modify files using familiar filesystem-like calls. Behind the scenes, the Sync API takes care of syncing changes to Dropbox and notifying your app when changes are made in Dropbox, so you can update your UI instantly.
This reference details the full set of classes used to interact with the Sync API. For more information on how to get started developing with the Sync API, see the Sync API tutorial.
In addition to files, Dropbox apps can also use datastores, which are ideal for keeping per-user data — like settings, bookmarks, or game state — in sync across multiple devices and operating systems. Datastores are simple embedded databases, which are synced to Dropbox. This SDK also includes datastore functionality, though it is covered in the separate Datastore API documentation.
All classes and methods in the API are thread-safe unless otherwise marked. Writing a new version of a file is an atomic operation, and will be immediately visible to other threads in this process, and uploaded to the server in the background. Other file system changes, such as moving or deleting a file will be applied atomically in the same way. Remote changes from the server are integrated into the file system atomically in the background. If your app uses multiple threads, and requires synchronization across changes to multiple files, or across a read-modify-write sequence, you should synchronize at a higher level using locks, or serialize access to the API through a single thread. If your app uses multiple processes, you must make use of the Sync API in only a single process, to avoid conflicting access to the cache on disk.
The account manager is responsible for linking new users and persisting account information across runs of your app. You typically create an account manager at app startup with your app key and secret and keep it until your app terminates.
+ (void)setSharedManager:(DBAccountManager *)sharedManager
A convenient place to store your app’s account manager.
+ (DBAccountManager *)sharedManager
A convenient place to get your app’s account manager.
@property (nonatomic, readonly) DBAccount *linkedAccount
The most recently linked account, or nil
if there are no accounts currently linked.
If your app needs to link multiple accounts at the same time, you should use the linkedAccounts property.
@property (nonatomic, readonly) NSArray *linkedAccounts
All currently linked accounts, or nil
if there are no accounts currently linked.
The accounts are ordered from the least recently to the most recently linked.
- (id)initWithAppKey:(NSString *)key secret:(NSString *)secret
Create a new account manager with your app’s app key and secret. You can register your app or find your key at the apps page.
- (void)linkFromWindow:(NSWindow *)parentWindow withCompletionBlock:(DBLinkCompletionBlock)block
This method begins the process for linking new accounts.
This will open the auth flow in a sheet. If parentWindow is nil
it will open in a new window.
When the user exits the flow, block
will be called with the linked account which might be nil
if the user cancelled or if there were errors.
Your app can call this method repeatedly to link more than one account (such as personal and a business account).
parentWindow
the parent window the auth flow modal should be attached to.
block
the block that gets called when the user is done linking.
- (void)addObserver:(id)observer block:(DBAccountManagerObserver)block
Add block
as an observer to get called whenever a new account is linked or an existing
account is unlinked. The observer will be called regardless of whether the account was
unlinked using -[DBAccount unlink]
or by the user on the Dropbox website.
observer
this is only used as a handle to unregister blocks with the removeObserver: method.
- (void)removeObserver:(id)observer
Use this method to remove all blocks associated with observer
.
observer
the same value you provided to the addObserver:block: method.
typedef void (^DBObserver)()
A generic block type used for observing changes throughout the Sync API
typedef void (^DBAccountManagerObserver)(DBAccount *account)
An observer for the linkedAccount property
typedef void (^DBLinkCompletionBlock)(DBAccount *account)
A completion block called after linking with linkFromWindow:withCompletionBlock:
The account represents a particular user who has linked their account to your app. You can get account objects from the account manager.
@property (nonatomic, readonly) NSString *userId
The user id of the account. This can be used to associate metadata with a given account.
@property (nonatomic, readonly, getter=isLinked) BOOL linked
Whether the account is currently linked. Note that accounts can be unlinked via the unlink method or from the Dropbox website.
@property (nonatomic, readonly) DBAccountInfo *info
Information about the user of this account, or nil
if no info is available.
Account info is fetched in the background. To be notified when account info is
available or updated, use addObserver:block:.
- (void)unlink
This method unlinks a user’s account from your app.
Once an account is unlinked, the local cache is deleted. If there is a filesystem object created with this account it will stop running.
- (void)addObserver:(id)observer block:(DBObserver)block
- (void)removeObserver:(id)observer
Remove all blocks associated with observer
by the addObserver:block: method.
Information about a user’s account.
@property (nonatomic, readonly) NSString *displayName
The recommended string to display to identify an account.
This is “userName” if orgName
is nil
, otherwise it’s “userName (orgName)”.
@property (nonatomic, readonly) NSString *userName
The user’s name.
@property (nonatomic, readonly) NSString *orgName
The user’s organization’s name if available, or nil
otherwise.
The DBError
class is a subclass of NSError
that always has domain
set to DBErrorDomain
.
Any method expected to fail will return a DBError
object via the last parameter.
Additionally, errors that happen in the background via syncing can also be retrieved, such
as the error property on DBFileStatus.
Some failures (those which represent bugs or internal errors) will instead raise a DBException
when they occur in an API method. A DBError
will still be used if such a failure occurs
on a background thread.
- (DBErrorCode)dbErrorCode
Same as code
. The code on a DBError object is always listed in the DBErrorCode enum.
typedef enum DBErrorCode
The type of error that occurred. It will be one of the following codes. Note that those codes marked as "Fatal" will generally cause exceptions rather than being returned as DBError. However you may see those codes in background sync status.
DBErrorInternal | Internal error or assertion in the SDK (Fatal) |
DBErrorCache | Failure accessing local cached data (Fatal) |
DBErrorShutdown | Attempt to use an object or send a request after shutdown (Fatal) |
DBErrorClosed | Use of an object which has been closed. (Fatal) |
DBErrorDeleted | Use of an object which has been deleted. Used for synchronous local state transitions,
not remote deletion (see DBErrorNotFound ) (Fatal) |
DBErrorBadType | Attempt to access a value of the wrong type (Fatal) |
DBErrorSizeLimit | Exceeding a fixed limit, such as maximum Datastore size. Not used for
account quota which is subject to change (see DBErrorQuota ). (Fatal) |
DBErrorBadIndex | Bad index into a list (Fatal) |
DBErrorIllegalArgument | Illegal argument to an API method (Fatal) |
DBErrorBadKey | Bad key in an internal map lookup (Fatal) |
DBErrorBadState | An object is in a bad state for an attempted operation (Fatal) |
DBErrorMemory | Out of memory (Fatal) |
DBErrorSystem | Error for the OS, when accessing private files or other OS resources (Fatal) |
DBErrorNotCached | Unable to read a file because it is unavailable in the cache (Fatal) |
DBErrorInvalidOperation | Attempt to perform an illegal operation, such as opening a directory, or deleting the root |
DBErrorNotFound | File, folder, or datastore does not exist |
DBErrorExists | Operation failed because the target already exists |
DBErrorAlreadyOpen | Attempt to open a file or datastore which is already open |
DBErrorParent | Parent directories are missing or not directories |
DBErrorDiskSpace | Out of disk space for file storage. Applies to local disk space,
not Dropbox quota (see DBErrorQuota ) |
DBErrorDisallowed | The app attempted an operation that isn't allowed by its access level, or that the user does not have permission to perform |
DBErrorFileIO | An error accessing a file (outside of the SDK's cache) |
DBErrorCancelled | An operation was cancelled |
DBErrorReadOnly | An operation try to act on a read-only file or folder |
DBErrorNetwork | An error occurred making a network request |
DBErrorTimeout | A connection timed out |
DBErrorNoConnection | No network connection available |
DBErrorSSL | Failure in SSL security or unable to verify the server's SSL certificate. Often caused by an out-of-date clock |
DBErrorServer | The server reported an error |
DBErrorAuth | The user has not authorized this app, or has unlinked this app |
DBErrorQuota | The user's Dropbox space is full |
DBErrorRequest | Server indicated that a request is invalid |
DBErrorResponse | The server returned an invalid response |
DBErrorRetryLater | The client should wait a while and then repeat the request |
DBErrorParamsNoThumb | No thumbnail is available |
The DBException
class is a subclass of NSException
that always has name
set to
DBExceptionName
. A DBException
is raised by a failure in an API method which indicates
programming errors or internal SDK problems.
You should generally not have to catch a DBException
, but the error
property will allow you
to classify or translate one if you need to.
@property (nonatomic, readonly) DBError *error
Information about the error which caused this exception to be raised.
The filesystem object provides a files and folder view of a user’s Dropbox. The most basic operations are listing a folder and opening a file, but it also allows you to move, delete, and create files and folders. The filesystem automatically synchronizes changes with the Dropbox server in the background.
File and folder info for a user’s Dropbox is mirrored locally and synced in the background.
The content of a file is not downloaded until the file is opened, after which it is cached
locally, up to a configured maximum size (defaulting to 500MB). If the file cache grows beyond
the maximum size, the least recently used files will be removed from the cache to free space.
Cached files will never be removed while in use: i.e. when a DBFile
is open, or
when there is an outstanding upload or download, so it is possible for the cache to temporarily
exceed the limit. The cache size can be set to zero, in which case files are removed from the
cache as soon as they are no longer in-use.
Background syncing will remain active if there are outstanding changes to upload or download, if there are open files, or if there are any observers registered for paths. Otherwise, syncing will be paused to preserve battery life until you access the filesystem again.
A DBFilesystem
instance is tied to a linked user account, and will be shut down if the account
is unlinked. In this case, most methods will fail with an error code of DBErrorAuth
.
+ (void)setSharedFilesystem:(DBFilesystem *)filesystem
A convienent place to store your app’s filesystem
+ (DBFilesystem *)sharedFilesystem
A convienent place to get your app’s filesystem
@property (nonatomic, readonly) DBAccount *account
The account object this filesystem was created with.
@property (nonatomic, readonly) BOOL completedFirstSync
When a user’s account is first linked, the filesystem needs to be synced with the server before it can be used. This property indicates whether the first sync has completed and the filesystem is ready to use.
@property (nonatomic, readonly, getter=isShutDown) BOOL shutDown
Whether the filesystem is currently shut down. The filesystem will shut down if the account associated with this filesystem becomes unlinked.
@property (nonatomic, readonly) DBSyncStatus *status
The status of background synchronization.
@property (nonatomic, readonly) unsigned long long fileCacheSize
The current total disk space consumed by files in the cache.
@property (nonatomic, assign) unsigned long long maxFileCacheSize
The configured maximum size of files in the cache.
Once set, this setting will remain in effect across app restarts. When the cache size is lowered, this method will immediately clean up the cache based on the new limit. See the class documentation for more information on cache management.
- (id)initWithAccount:(DBAccount *)account
Create a new filesystem object with a linked account from the account manager.
- (NSArray *)listFolder:(DBPath *)path error:(DBError **)error
Returns a list of DBFileInfo objects representing the files contained in the folder at path
.
If completedFirstSync is false, then this call will block until the first sync completes or an
error occurs.
An array of DBFileInfo objects if successful, or nil
if an error occurred.
- (DBFileInfo *)fileInfoForPath:(DBPath *)path error:(DBError **)error
Returns the file info for the file or folder at path
, or
nil
if an error occurred. If there is no file or folder at path
, returns
nil
and sets error
to DBErrorParamsNotFound
.
- (DBFile *)openFile:(DBPath *)path error:(DBError **)error
Opens an existing file and returns a file object representing the file at path
.
Files are opened at the newest cached version if the file is cached. Otherwise, the file will
open at the latest server version and start downloading. Check the status
property of the
returned file object to determine whether it’s cached. Only 1 file can be open at a given path at
the same time.
The file object if the file was opened successfully, or nil
if an error
occurred.
- (DBFile *)createFile:(DBPath *)path error:(DBError **)error
Creates a new file at path
and returns a file object open at that path.
The newly created file object if the file was opened successfuly, or nil
if an
error occurred.
- (DBFile *)openThumbnail:(DBPath *)path ofSize:(DBThumbSize)size inFormat:(DBThumbFormat)format error:(DBError **)error
Opens a thumbnail for an existing file and returns a file object
representing a thumbnail for the file at path
.
Thumbnails are opened at the newest cached version if the thumbnail is cached.
Otherwise, the thumbnail will open at the latest version and start downloading.
Check the status
property of the returned file object to determine whether
it’s cached.
Thumbnails are generated on the server and cached separately. When offline
a thumbnail might be unavailable even if the file contents are available. If
a file is modified locally, the thumbnail will not be available until its
upload completes. Check the thumbExists
property of the file’s info to
find out if a thumbnail is available for download.
The DBFile object representing a thumbnail is unrelated to any DBFile opened on the file itself. Thumbnails are read-only – any attempt to write will fail. It is possible to open multiple thumbnails (for instance, of different sizes) on the same path.
Thumbnails are scaled (not cropped) in a way which preserves the original images aspect ratio, to a size which fits within a bounding box defined by the size parameter.
The file object if the thumbnail was opened successfully, or
nil
if an error occurred.
- (BOOL)createFolder:(DBPath *)path error:(DBError **)error
Creates a new folder at path
.
YES if the folder was created successfully, or NO if an error occurred.
- (BOOL)deletePath:(DBPath *)path error:(DBError **)error
Deletes the file or folder at path
.
YES if the file or folder was deleted successfully, or NO if an error occurred.
- (BOOL)movePath:(DBPath *)fromPath toPath:(DBPath *)toPath error:(DBError **)error
Moves a file or folder at fromPath
to toPath
.
YES if the file or folder was moved successfully, or NO if an error occurred.
- (NSString *)fetchShareLinkForPath:(DBPath *)path shorten:(BOOL)shorten error:(DBError **)error
Returns a link to the file or folder at path
, suitable for sharing. The link
will optionally be shortened using the Dropbox URL shortener.
If the file or folder was created locally but not yet uploaded, a link will be created, and viewing it before the upload is complete will result in a status page indicating the pending upload.
This requires a server request. It will fail if the app is offline. It shouldn’t be called on the main thread.
the link URL, or nil
if an error occurred.
- (BOOL)addObserver:(id)observer block:(DBObserver)block
Add an observer to be notified any time a property of the filesystem changes.
The block will be called anytime completedFirstSync, shutDown, or status changes.
- (BOOL)addObserver:(id)observer forPath:(DBPath *)path block:(DBObserver)block
Add an observer to be notified any time the file or folder at path
changes.
- (BOOL)addObserver:(id)observer forPathAndChildren:(DBPath *)path block:(DBObserver)block
Add an observer to be notified any time the folder at path
changes or a file or folder
directly contained in path
changes.
- (BOOL)addObserver:(id)observer forPathAndDescendants:(DBPath *)path block:(DBObserver)block
Add an observer to be notified any time the folder at path
changes or a file or folder
contained somewhere beneath path
changes.
- (void)removeObserver:(id)observer
Unregister all blocks associated with observer
from receiving updates.
- (void)shutDown
Shuts down the filesystem, which stops all syncing.
All associated DBFile
s will be closed. Changes that were made to files
before shutdown will be uploaded the next time a DBFilesystem
is created.
After this call, the DBFilesystem
and its DBFile
s can no longer be used.
You should get a new DBFilesystem
via initWithAccount:.
The filesystem will be automatically shut down if the app is unlinked remotely.
typedef enum DBThumbSize
Possible values for thumbnail size when opening a thumbnail. Thumbnails are scaled (not cropped) in a way which preserves the original images aspect ratio, to a size which fits within a bounding box defined by the size parameter.
DBThumbSizeXS | Thumbnail scaled to fit in a 32x32 bounding box. |
DBThumbSizeS | Thumbnail scaled to fit in a 64x64 bounding box. |
DBThumbSizeM | Thumbnail scaled to fit in a 128x128 bounding box. |
DBThumbSizeL | Thumbnail scaled to fit in a 640x480 bounding box. |
DBThumbSizeXL | Thumbnail scaled to fit in a 1024x768 bounding box. |
typedef enum DBThumbFormat
Possible values for thumbnail format when opening a thumbnail.
The available formats are:DBThumbFormatJPG | Thumbnail in JPG format |
DBThumbFormatPNG | Thumbnail in PNG format |
The current status of background synchronization for a DBFilesystem.
@property (nonatomic, readonly) BOOL active
Background synchronization is actively processing or waiting for changes. Syncing is active when a DBFilesystem is first created until it completes its first file info sync. After that point it is active whenever there are changes to download or upload, or when there are any files open or path observers registered.
@property (nonatomic, readonly) DBSyncOperationStatus *metadata
Status of synchronizing info about files and folders. Metadata sync is only considered in progress when it is actively processing new changes, not when it is simply watching for changes.
@property (nonatomic, readonly) DBSyncOperationStatus *download
Status of downloading file contents into the cache.
@property (nonatomic, readonly) DBSyncOperationStatus *upload
Status of uploading changes to the server. This includes changes to file contents, as well as creation, deletion, and renames.
@property (nonatomic, readonly) BOOL anyInProgress
Convenience property for checking whether any type of operation is in progress.
@property (nonatomic, readonly) DBSyncOperationStatus *anyError
The current status of one type of background synchronization operation in a DBFilesystem.
@property (nonatomic, readonly) BOOL inProgress
Indicates that operations are in progress or queued for retry.
@property (nonatomic, readonly) DBError *error
If the most recent operation failed, the failure is represented here.
Otherwise this field is nil
.
The path object represents a valid Dropbox path, and knows how to do correct path comparisons. It also has convenience methods for constructing new paths.
+ (DBPath *)root
The top-most folder in your app’s view of the user’s Dropbox.
- (id)initWithString:(NSString *)pathStr
Create a new path object from a string. Some special characters, names, or encodings a are not allowed in a Dropbox path. For more details see this article.
A new path object if the contents of pathStr
are a valid Dropbox path, nil
otherwise.
- (NSString *)name
The unqualified name of the file or folder at this path.
For the root, this will return the same as stringValue
.
- (DBPath *)childPath:(NSString *)childName
Create a new path by treating the current path as a path to a folder, and childName
as the
name of an item in that folder.
A new path, or nil
if childName
is invalid.
- (DBPath *)parent
Create a new path that is the folder containing the current path.
For the root, this will return the same as stringValue
.
A new path, or nil
if path is already at the root.
- (NSString *)stringValue
The fully qualified path (relative to the root) as a string, with original casing.
The file info class contains basic information about a file or folder.
@property (nonatomic, readonly) DBPath *path
The path of the file or folder.
@property (nonatomic, readonly) BOOL isFolder
Whether the item at path
is a folder or a file.
@property (nonatomic, readonly) NSDate *modifiedTime
The last time the file or folder was modified.
@property (nonatomic, readonly) long long size
The file’s size. This property is always 0 for folders.
@property (nonatomic, readonly) BOOL thumbExists
Whether a thumbnail for this file can be requested from the server, based on the file format. Since thumbnails are generated only by the server, this value will be false on a locally-modified file until it finishes uploading.
@property (nonatomic, readonly) NSString *iconName
The name of an appropriate icon to display for the file, taken
from the Dropbox icon library. Will be nil
if no suggested icon
is available. For more information see the
metadata
documentation.
The file object represents a particular file at a particular version. It has basic file operations such as reading and writing the file’s contents and getting info about the file. It can also tell you the current sync status, whether there’s a newer version available, and allows you to update to the newer version.
@property (nonatomic, readonly) DBFileInfo *info
The DBFileInfo for the file.
Note that the path of a file can change if a conflict occurs, so the value of
file.info.path
is not always equal to the path the file was opened at.
If this DBFile represents a thumbnail, the info still reflects the full file contents.
@property (nonatomic, readonly, getter=isOpen) BOOL open
Whether the file is currently open.
@property (nonatomic, readonly) DBFileStatus *status
The current sync status for the file or thumbnail version represented by this DBFile.
@property (nonatomic, readonly) DBFileStatus *newerStatus
The current sync status for the newer version of the file. If the file is the newest version,
then this property is nil
.
@property (nonatomic, readonly) BOOL isThumb
Whether this DBFile represents a thumbnail, rather than the file contents.
- (NSFileHandle *)readHandle:(DBError **)error
Returns a read-only file handle for the file. If the file is not cached then the method will block until the file is downloaded.
A file handle if the file can be read, or nil
if an error occurred.
- (NSData *)readData:(DBError **)error
A wrapper for readHandle: that reads the entire file contents into an NSData object.
The file’s contents if the file can be read, or nil
if an error occurred.
- (NSString *)readString:(DBError **)error
A wrapper for readHandle: that reads the entire file contents as a UTF8 encoded string.
The file’s contents decoded as UTF8 if the file can be read, or nil
if an error occurred.
- (BOOL)writeContentsOfFile:(NSString *)localPath shouldSteal:(BOOL)shouldSteal error:(DBError **)error
Updates the file’s contents with the contents of the file at localPath
.
shouldSteal
whether the file at localPath
should be moved from its
current location (i.e. “stolen”) into management by the Sync SDK, or if it must
be copied. If you are done with the file at localPath
, then stealing is more
efficient, but the behavior of writing to the file after stealing is undefined.
Stealing will fail if the source file is not on the same device as the
SDK cache, since it relies on the ability to rename without copying.
YES if the file was written successfully, or NO if an error occurred.
- (BOOL)writeData:(NSData *)data error:(DBError **)error
Updates the contents of the file to be the bytes stored in data
.
YES if the file was written successfully, or NO if an error occurred.
- (BOOL)writeString:(NSString *)string error:(DBError **)error
Updates the contents of the file with the parameter string
encoded in UTF8.
YES if the file was written successfully, or NO if an error occurred.
- (BOOL)appendData:(NSData *)data error:(DBError **)error
Apppends the data supplied to the end of the file. If the file is not cached, then the method will block until the file is downloaded.
YES if the data was appended to the file successfully, or NO if an error occurred.
- (BOOL)appendString:(NSString *)string error:(DBError **)error
Appends the UTF8 encoded string to the file. If the file is not cached, then the method will block until the file is downloaded.
YES if the string was appended to the file successfully, or NO if an error occured.
- (BOOL)update:(DBError **)error
If there is a newer version of the file available, and it’s cached (determined by the cached property on newerStatus), then this method will update the file object to reference the newer version so it can be read from or written to.
YES if the file was written successfully, or NO if an error occurred.
- (void)close
Closes the file, preventing any further operations to occur and allowing the file to be opened again. This happens automatically when the object is deallocated.
- (void)addObserver:(id)observer block:(DBObserver)block
Add block
as an observer when a property of the file changes.
- (void)removeObserver:(id)observer
Remove all blocks registered for the given observer
.
The file status object exposes information about the file’s current sync status, including whether it’s cached, if it’s uploading or downloading, and the progress of an upload or download.
@property (nonatomic, readonly) BOOL cached
Whether the contents of the file are cached locally and can be read without making a network request.
@property (nonatomic, readonly) DBFileState state
Whether the file is currently uploading, downloading, or neither (idle)
@property (nonatomic, readonly) float progress
If the file is transferring, the progress of the transfer, between 0 and 1.
@property (nonatomic, readonly) DBError *error
If the file needs to be transferred, but can’t for whatever reason (such as no internet connection), then this property is set to the last error that prevented the transfer.
typedef enum DBFileState
An enum representing the current sync status of the file. Its possible values are:
DBFileStateDownloading | The file is currently downloading |
DBFileStateUploading | The file is currently uploading |
DBFileStateIdle | The file is neither uploading or downloading |