我正在尝试实现一个包含从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
Run Code Online (Sandbox Code Playgroud)
我通过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 :)
Run Code Online (Sandbox Code Playgroud)
上面的代码用于以过程方式从流中读取(将阻塞线程).要异步读取流,请参阅另一个答案(Stream to Get Data - NSInputStream).希望这有帮助.
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |