如何在Dropbox API v2中检查文件或文件夹?附Objective-C代码
用Dropbox API v2(Objective-C)检查文件/文件夹的完整实现
我来帮你把这段代码补全,同时梳理清楚两种常见的文件/文件夹检查场景的实现方式:
一、场景1:列出指定路径下的所有文件和文件夹(用listFolder)
这是你最初代码的延伸,用来遍历目标路径下的所有条目,完整实现包括权限适配、错误处理和结果解析:
// 1. 先确认用户已授权Dropbox DBUserClient *client = [DBClientsManager authorizedClient]; if (!client) { // 处理未授权场景,比如弹窗引导用户登录 NSLog(@"请先完成Dropbox授权登录"); return; } // 2. 根据App权限设置目标路径 // - 若App是「Full Dropbox」权限:可填根目录@"",或具体路径如@"/Photos" // - 若App是「App Folder」权限:直接填@""即可(SDK会自动映射到你的App专属文件夹) NSString *path = @""; // 3. 调用listFolder接口获取目录内容 [[client.filesRoutes listFolder:path] setResponseBlock:^(DBFILESListFolderResult *result, DBFILESListFolderError *routeError, DBRequestError *networkError) { // 优先处理网络层面的错误 if (networkError) { NSLog(@"网络请求失败:%@", networkError.localizedDescription); return; } // 处理路由级错误(比如路径不存在、权限不足) if (routeError) { if (routeError.isPath) { NSLog(@"路径错误:%@", routeError.pathValue.localizedDescription); } else { NSLog(@"请求异常:%@", routeError.localizedDescription); } return; } // 成功获取结果,遍历解析条目 if (result) { for (DBFILESMetadata *entry in result.entries) { // 区分文件和文件夹 if ([entry isKindOfClass:[DBFILESFileMetadata class]]) { DBFILESFileMetadata *fileMeta = (DBFILESFileMetadata *)entry; NSLog(@"找到文件:%@,大小:%lld字节", fileMeta.name, fileMeta.size); } else if ([entry isKindOfClass:[DBFILESFolderMetadata class]]) { DBFILESFolderMetadata *folderMeta = (DBFILESFolderMetadata *)entry; NSLog(@"找到文件夹:%@", folderMeta.name); } } // 处理分页:如果目录条目过多,会返回cursor用于获取下一页内容 if (result.hasMore) { [[client.filesRoutes listFolderContinue:result.cursor] setResponseBlock:^(DBFILESListFolderResult *nextResult, DBFILESListFolderContinueError *nextRouteError, DBRequestError *nextNetworkError) { // 下一页结果的处理逻辑和上面一致 }]; } } }];
二、场景2:检查单个文件/文件夹是否存在(用getMetadata)
如果你只是想确认某个特定路径的文件/文件夹是否存在,用getMetadata会更高效,不需要遍历整个目录:
DBUserClient *client = [DBClientsManager authorizedClient]; if (!client) { NSLog(@"请先完成Dropbox授权登录"); return; } // 要检查的目标路径,比如@"/test.txt"或@"/MyFolder" NSString *targetPath = @"/test.txt"; [[client.filesRoutes getMetadata:targetPath] setResponseBlock:^(DBFILESMetadata *result, DBFILESGetMetadataError *routeError, DBRequestError *networkError) { if (networkError) { NSLog(@"网络请求失败:%@", networkError.localizedDescription); return; } if (routeError) { if (routeError.isPath && routeError.pathValue.isNotFound) { // 明确判断:目标路径不存在 NSLog(@"目标文件/文件夹不存在"); } else { NSLog(@"请求异常:%@", routeError.localizedDescription); } return; } // 路径存在,区分文件/文件夹 if ([result isKindOfClass:[DBFILESFileMetadata class]]) { NSLog(@"存在文件:%@", result.name); } else if ([result isKindOfClass:[DBFILESFolderMetadata class]]) { NSLog(@"存在文件夹:%@", result.name); } }];
关键注意事项
- 权限匹配:务必保证你的Dropbox App权限(Full Dropbox/App Folder)和设置的路径对应,否则会触发权限错误
- 错误覆盖:不要忽略网络错误和路由错误,比如用户未授权、路径不存在、网络断开等场景都要处理
- 分页逻辑:如果目标目录下有大量条目,
listFolder会返回分页结果,需要用cursor调用listFolderContinue获取剩余内容
内容的提问来源于stack exchange,提问作者Ali John
相关产品推荐
相关产品推荐

