Iphone 如何使用url获取json数据并将其写入文件?

Iphone 如何使用url获取json数据并将其写入文件?,iphone,json,ios6,nsdocumentdirectory,Iphone,Json,Ios6,Nsdocumentdirectory,正如我上面的屏幕截图所示,我的应用程序中有一个json文件(productDetail.json),然后我从json数据编写文件,如下面的代码所示 else if([(MultipleURLConnection *)connection tag]==2) { if([fn writeToFile:responseData fileName:@"productDetail.json"]) [self performSelector:@selector(loadingJSO

正如我上面的屏幕截图所示,我的应用程序中有一个json文件(productDetail.json),然后我从json数据编写文件,如下面的代码所示

else if([(MultipleURLConnection *)connection tag]==2)
    {
  if([fn writeToFile:responseData fileName:@"productDetail.json"])
       [self performSelector:@selector(loadingJSON) withObject:nil afterDelay:0.1];
    }
在上面的代码中,responseData是NSMutableData,fn是函数类对象名,我在下面的方法中使用了这个名称

- (BOOL)writeToFile:(NSData *)data fileName:(NSString *)fileName 
 {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:myFile])  // if file doesn't exist, create it
    return ([fm createFileAtPath:myFile contents:data attributes:nil]);
else
    return ([data writeToFile:myFile atomically:YES]);  
 }
现在我决定从应用程序中删除json文件,并将其放在服务器上,然后获取它

else if([(MultipleURLConnection *)connection tag]==2)
    {
        NSURL *url = [NSURL URLWithString:@"http://mysite.com/Infomist/productDetail.json"];
        NSData *jsonData = [NSData dataWithContentsOfURL:url];

        if(jsonData != nil)
        {
            NSError *error = nil;

            id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
            if (error == nil)
              NSLog(@"show data %@",result);
       }
现在上面的方法成功地从服务器获取了我的数据,它在NSlog中显示了我的所有数据,但现在我的问题是如何修改这个方法

     if([fn writeToFile:responseData fileName:@"])
因为在将json文件放到服务器上之后,我没有任何文件可以在上面的方法中传递文件名来调用

- (BOOL)writeToFile:(NSData *)data fileName:(NSString *)fileName  .
我已经有本地json文件的应用程序流,所以我只需要在我的应用程序中写入json数据

- (BOOL)writeToFile:(NSData *)data fileName:(NSString *)fileName 
以上要求
NSData
作为参数

        id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
上面给出了返回类型对象的
id
。您需要检查它使用的对象类型
isKindOfClass

然后使用解码/NSkeyedArchiver或其他技术将其转换为数据