About this Blog

This Blog has English posts and Japanese posts. About Mac, iOS, Objective-C, and so on.

2012年11月19日月曜日

iOSのDopbox SDKを使ったアプリで、キャッシュよりも日付が新しかったらダウンロードする

DropboxのSDKでは、NSDocumentDirectoryにファイルを保存するようになっています。
restClient:loadedFile:メソッドを使うと、とにかくダウンロードしてしまうので、先にファイルの日付を比較し、Dropboxサーバー上のファイルが新しかったらダウンロードするようなコードを書きました。 Dropbox SDKの導入については、以下の記事を参考にしました。

Dropboxアプリ制作の流れ - teru_kusuの日記
[iPhone/iPad] Dropbox API を使ってみた | Sun Limited Mt.


DBRestClientDelegateを設定したクラスで、

インスタンス変数として、
    _dropbboxFilePath
    _localFilePath
を用意します。

_dropbboxFilePathはDropboxにあるファイルのパス、
_localFilePathはNSDocumentDirectoryを使って、
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    _localFilePath = [[documentDirectory stringByAppendingFormat:_dropbboxFilePath] retain];
と設定してあります。 そして、以下のようなメソッドを作ります。
-(void)loadIfFileModified{
     [[self restClient] loadMetadata:_dropbboxFilePath];
}

- (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata{
    NSFileManager *fmanager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSDictionary *attr = [fmanager attributesOfItemAtPath:_localFilePath error:&error];
    if([[metadata lastModifiedDate] compare:[attr fileModificationDate]]==NSOrderedDescending || error){
        //Dropbox上のファイルが更新されていたときの処理
        //エラーでもダウンロードを試みる
        //_dropboxFilePathのファイルを、_localFilePathに保存
        [[self restClient] loadFile:_dropbboxFilePath intoPath:_localFilePath];
    }else{
        //Dropbox上のファイルが更新されていなかったときの処理
    }
}
-(void)restClient:(DBRestClient *)client loadedFile:(NSString *)destPath{
    //ダウンロード完了後の処理
}


日付の比較については、以下の記事を参考にしました。
objective-Cでの日付の比較について

0 件のコメント:

コメントを投稿