2
votes

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

1 Answers

0
votes

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