我正在尝试实现一个应用程序,其中包括从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工具检查了网络和磁盘活动,下载操作是正确的,所以我相信这与下载函数的返回有关。
发布于 2016-06-17 16:43:26
首先,该方法的返回类型是一个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)。希望这能帮上忙。
https://stackoverflow.com/questions/37886427
复制相似问题