2013-02-14 47 views
0

我正試圖下載並緩存iPhone文檔目錄中的數據。我希望能夠檢查文件是否存在,並使用本地數據填充我的UITableViewCell(如果存在),並在遠程加載數據(如果不存在)。如何確定某個名稱的文件是否存在於我的iOS文檔目錄中

這是我用來下載數據的代碼。

NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *path = [paths objectAtIndex:0]; 
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     NSLog(@"Successfully downloaded file to %@", path); 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"The Error Is: %@", error); 
    }]; 
+0

NSFileManager有一個方法來查看文件是否存在於路徑中。 – rmaddy 2013-02-14 21:51:01

回答

2
NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSString *pathToMyFile = [path stringByAppendingPathComponent:@"myDataFile"]; 
if ([fileManager fileExistsAtPath:pathToMyFile]) { 
    // file exists 
} 
else { 
    // file doesn't exist 
} 
0

你想要的文件目錄嗎?使用此代碼:

NSString* documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"FILENAME"]; 
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 
    // file exists 
} 
else { 
    // file doesn't exist 
} 

注意:您可能要檢查是否AFNetworking在創建用於存儲任何它下載文件路徑的目錄。這些庫通常創建自己的目錄。

相關問題