我正在尝试实现一个包含从 Dropbox 下载文件的应用程序。看起来有一个简单直接的框架可以做到这一点(CloudRail)。但是当我尝试使用下载的文件(在本例中为图像)时代码崩溃,这是示例:
self.dropboxInstance = [[Dropbox alloc] initWithClientId:self.authDic[@“————“] clientSecret:self.authDic[@“————“]];
id returnObject = [self.dropboxInstance downloadWithFilePath:@“/pictures/001.png“];
UIImage * image = [UIImage imageWithData:object]; // CRASH HERE
我通过Xcode工具检查了网络和磁盘事件,下载正确执行,所以我认为这与下载功能的返回有关。
最佳答案
首先,该方法的返回类型是一个NSInputStream,可以用来读取你下载的文件的内容。
代码不起作用的原因是因为您将其视为 NSData 类型。
因此,解决方案是首先从作为返回接收的流中读取所有内容,将其存储在 NSData 对象中,然后从数据创建 UIImage。
self.dropboxInstance = [[Dropbox alloc] initWithClientId:self.authDic[@“————“] clientSecret:self.authDic[@“————“]];
id returnObject = [self.dropboxInstance downloadWithFilePath:@“/pictures/001.png“];
//NEW CODE
NSInputStream * inputStream = returnObject;
[inputStream open];
NSInteger result;
uint8_t buffer[1024]; // buffer of 1kB
while((result = [inputStream read:buffer maxLength:1024]) != 0) {
if(result > 0) {
// buffer contains result bytes of data to be handled
[data appendBytes:buffer length:result];
} else {
// The stream had an error. You can get an NSError object using [iStream streamError]
if (result<0) {
[NSException raise:@"STREAM_ERROR" format:@"%@", [inputStream streamError]];
}
}
}
//END NEWCODE
UIImage * image = [UIImage imageWithData:data]; // NO CRASH ANYMORE :)
上面的代码用于以程序方式从流中读取(会阻塞线程)。要异步读取流,请参阅另一个答案( Stream to Get Data - NSInputStream )。希望这有帮助。
关于cloudrail - 使用 CloudRail 进行简单下载失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37886427/