アプリケーション起動時にDBAccountManagerを作成する。
Dropboxの初期化
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
DBAccountManager *accountManager = [[DBAccountManager alloc] initWithAppKey:APP_KEY secret:APP_SECRET];
[DBAccountManager setSharedManager:accountManager];
linkボタンなどを用意しておき、Dropboxへ接続する。
Dropboxに接続しにいく
[[DBAccountManager sharedManager] linkFromController:self.parentViewController];
いつものDropboxへのログイン画面が表示され、無事にログインできたらDBAccountを作成する。
接続できた!
- (BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
DBAccount *account = [[DBAccountManager sharedManager] handleOpenURL:url];
if (account) {
NSLog(@"Dropbox connected.");
}
return YES;
}
試しに、ファイルを作成してみる。
ファイル作成
DBFilesystem *filesystem = [[DBFilesystem alloc] initWithAccount:account];
[DBFilesystem setSharedFilesystem:filesystem];
NSError *error = nil;
DBPath *newPath = [[DBPath root] childPath:@"hello.txt"];
DBFile *file = [[DBFilesystem sharedFilesystem] createFile:newPath error:&error];
if (file == nil) {
NSLog(@"createFile error[%@]", [error localizedDescription]);
abort();
}
if (! [file writeString:@"Hello World!" error:&error]) {
NSLog(@"writeString error[%@]", [error localizedDescription]);
abort();
}
Dropboxのフォルダにhello.txtファイルが作成され、「Hello World!」と書き込まれている。
今度は、ファイルを読んでみる。
ファイル読み込み
DBPath *existingPath = [[DBPath root] childPath:@"hello.txt"];
DBFile *file = [[DBFilesystem sharedFilesystem] openFile:existingPath error:&error];
if (file == nil) {
NSLog(@"openFile error[%@]", [error localizedDescription]);
abort();
}
NSString *contents = [file readString:&error];
if (contents == nil) {
NSLog(@"readString error[%@]", [error localizedDescription]);
abort();
}
NSLog(@"contents[%@]", contents);
無事にファイルを読めました。
一度接続してしまえば、オフラインでもファイルの読み書きが可能みたいです。