如何将文件Blob转换为NSData? [英] How to convert a File Blob to NSData?

查看:63
本文介绍了如何将文件Blob转换为NSData?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将将来自Web服务的文件Blob转换为NSData对象时遇到问题.文件Blob可以是任何类型的文件.我可以通过RestKit向Web服务器请求文件,并得到以下响应:

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"
}]

我通过JSONKit将Response转换为Dictionary NSDictionary * dict = [[response bodyAsString] objectFromJSONString]; 正常工作.但是我不知道如何将FileBlob转换为NSData对象,以便可以将其作为文件写入HDD.如果是上面示例中的txt文件,我可以遍历数组并将所有整数值转换为chars

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];

但是,如果文件是其他类似pdf的文件,则此文件不起作用.我有什么办法可以将File Blob转换为NSData Object或将Blob作为文件写入磁盘吗?

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秒登录
发送“验证码”获取 | 15天全站免登陆