4

我正在尝试实现一个包括从 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工具检查了网络和磁盘活动,下载是正确的,所以我相信这与下载功能的返回有关。

4

1 回答 1

5

首先,该方法的返回类型是一个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)。希望这有帮助。

于 2016-06-17T16:43:26.867 回答