How to convert a File Blob to NSData?

天大地大妈咪最大 提交于 2019-12-11 03:02:55

问题


I have a problem converting a File Blob comming from a Webservice to an NSData Object. The File Blob can be any type of file. I can request a file from a Webserver via RestKit and get the following response:

[{
   "FileBlob":    [
      65,
      108,
      108,
      111,
      99,
      46,
      32,
      83,
      /* more integer values omitted */
   ],
   "FileID": 1234567890,
   "FileName": "name.txt"
}]

I convert the Response into a Dictionary via JSONKit NSDictionary *dict = [[response bodyAsString] objectFromJSONString]; which works fine. But i cannot figure out how to convert the FileBlob into a NSData Object so that i can write it as a file onto the HDD. In case of a txt-File like in the example above i can go trough the array and convert all integer Values to chars

NSMutableString *fileString = [NSMutableString string];
for (NSNumber *value in [[dict valueForKey:@"FileBlob"] objectAtIndex:0]) {
    [fileString appendFormat:@"%c", (char)value.integerValue];
}

and then save everything to disk

NSData *data = [fileString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *file = [[paths objectAtIndex:0] stringByAppendingPathComponent:filename];        
[[NSFileManager defaultManager] createFileAtPath:file contents:data attributes:nil];

But if the file is something else like a pdf this does not work. Is there anything i can do, to convert the File Blob to an NSData Object or anything else to write the blob as a file onto the disc?


回答1:


Use NSMutableData instead:

NSMutableData *data = [NSMutableData dataWithCapacity:blobs.count];

for (NSNumber *number in blobs)
{
    uint8_t byte = (uint8_t)[number intValue];
    [data appendBytes:&byte length:1];
}

// write data to file


来源:https://stackoverflow.com/questions/9556170/how-to-convert-a-file-blob-to-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!