Sync API for OS X documentation

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.

General information

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.

DBAccountManager

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.

Class methods
  • + (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.

Properties
  • @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.

Instance methods
  • - (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).

    Parameters

    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.

    Parameters

    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.

    Parameters

    observer

    the same value you provided to the addObserver:block: method.

Constants
  • 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:

DBAccount

The account represents a particular user who has linked their account to your app. You can get account objects from the account manager.

Properties
  • @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:.

Instance methods
  • 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

    Add block as an observer of an account to get notified whenever the account’s linked or info properties change.

  • - (void)removeObserver:(id)observer

    Remove all blocks associated with observer by the addObserver:block: method.

DBAccountInfo

Information about a user’s account.

Properties
  • @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.

DBError

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.

Instance methods
  • - (DBErrorCode)dbErrorCode

    Same as code. The code on a DBError object is always listed in the DBErrorCode enum.

Constants
  • 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.

    DBErrorInternalInternal error or assertion in the SDK (Fatal)
    DBErrorCacheFailure accessing local cached data (Fatal)
    DBErrorShutdownAttempt to use an object or send a request after shutdown (Fatal)
    DBErrorClosedUse of an object which has been closed. (Fatal)
    DBErrorDeletedUse of an object which has been deleted. Used for synchronous local state transitions, not remote deletion (see DBErrorNotFound) (Fatal)
    DBErrorBadTypeAttempt to access a value of the wrong type (Fatal)
    DBErrorSizeLimitExceeding a fixed limit, such as maximum Datastore size. Not used for account quota which is subject to change (see DBErrorQuota). (Fatal)
    DBErrorBadIndexBad index into a list (Fatal)
    DBErrorIllegalArgumentIllegal argument to an API method (Fatal)
    DBErrorBadKeyBad key in an internal map lookup (Fatal)
    DBErrorBadStateAn object is in a bad state for an attempted operation (Fatal)
    DBErrorMemoryOut of memory (Fatal)
    DBErrorSystemError for the OS, when accessing private files or other OS resources (Fatal)
    DBErrorNotCachedUnable to read a file because it is unavailable in the cache (Fatal)
    DBErrorInvalidOperationAttempt to perform an illegal operation, such as opening a directory, or deleting the root
    DBErrorNotFoundFile, folder, or datastore does not exist
    DBErrorExistsOperation failed because the target already exists
    DBErrorAlreadyOpenAttempt to open a file or datastore which is already open
    DBErrorParentParent directories are missing or not directories
    DBErrorDiskSpaceOut of disk space for file storage. Applies to local disk space, not Dropbox quota (see DBErrorQuota)
    DBErrorDisallowedThe app attempted an operation that isn't allowed by its access level, or that the user does not have permission to perform
    DBErrorFileIOAn error accessing a file (outside of the SDK's cache)
    DBErrorCancelledAn operation was cancelled
    DBErrorReadOnlyAn operation try to act on a read-only file or folder
    DBErrorNetworkAn error occurred making a network request
    DBErrorTimeoutA connection timed out
    DBErrorNoConnectionNo network connection available
    DBErrorSSLFailure in SSL security or unable to verify the server's SSL certificate. Often caused by an out-of-date clock
    DBErrorServerThe server reported an error
    DBErrorAuthThe user has not authorized this app, or has unlinked this app
    DBErrorQuotaThe user's Dropbox space is full
    DBErrorRequestServer indicated that a request is invalid
    DBErrorResponseThe server returned an invalid response
    DBErrorRetryLaterThe client should wait a while and then repeat the request
    DBErrorParamsNoThumbNo thumbnail is available

DBException

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.

Properties
  • @property (nonatomic, readonly) DBError *error

    Information about the error which caused this exception to be raised.

DBFilesystem

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.

Class methods
  • + (void)setSharedFilesystem:(DBFilesystem *)filesystem

    A convienent place to store your app’s filesystem

  • + (DBFilesystem *)sharedFilesystem

    A convienent place to get your app’s filesystem

Properties
  • @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.

Instance methods
  • - (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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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 DBFiles 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 DBFiles 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.

Constants
  • 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.

    DBThumbSizeXSThumbnail scaled to fit in a 32x32 bounding box.
    DBThumbSizeSThumbnail scaled to fit in a 64x64 bounding box.
    DBThumbSizeMThumbnail scaled to fit in a 128x128 bounding box.
    DBThumbSizeLThumbnail scaled to fit in a 640x480 bounding box.
    DBThumbSizeXLThumbnail scaled to fit in a 1024x768 bounding box.
  • typedef enum DBThumbFormat

    Possible values for thumbnail format when opening a thumbnail.

    The available formats are:

    DBThumbFormatJPGThumbnail in JPG format
    DBThumbFormatPNGThumbnail in PNG format

DBSyncStatus

The current status of background synchronization for a DBFilesystem.

Properties
  • @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

    Convenience property for determining whether any operation failed, and getting an appropriate DBError. If there are multiple failures, the DBError returned will be taken from metadata, download, or upload status in that order.

DBSyncOperationStatus

The current status of one type of background synchronization operation in a DBFilesystem.

Properties
  • @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.

DBPath

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.

Class methods
  • + (DBPath *)root

    The top-most folder in your app’s view of the user’s Dropbox.

Instance methods
  • - (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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

DBFileInfo

The file info class contains basic information about a file or folder.

Properties
  • @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.

DBFile

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.

Properties
  • @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.

Instance methods
  • - (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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Parameters

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

    Returns

    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.

DBFileStatus

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.

Properties
  • @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.

Constants
  • typedef enum DBFileState

    An enum representing the current sync status of the file. Its possible values are:

    DBFileStateDownloadingThe file is currently downloading
    DBFileStateUploadingThe file is currently uploading
    DBFileStateIdleThe file is neither uploading or downloading