ios 如何从 URL 中获取数据,使用 xcode 4.3.1 和 NSJSONSerialization 类参考

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9753229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:23:03  来源:igfitidea点击:

How do I fetch data from URL, using xcode 4.3.1 with NSJSONSerialization Class Reference

iphoneiosjsonxcode4.3nsjsonserialization

提问by CustomCase

I am trying to get my head around the NSJSONSerialization Class Reference. In the lack of a code-example at the developer.apple.com website, I′m lost. There are millions of examples all around the web with other json libaries, but I haven′t been able to get any of them to work with the latest build of xcode. (I′m running: Version 4.3.1 (4E1019) and testing on iPhone 5.0.1)

我正在尝试了解NSJSONSerialization Class Reference。由于缺乏 developer.apple.com 网站上的代码示例,我迷路了。网络上有数百万个带有其他 json 库的示例,但我无法让它们中的任何一个与最新版本的 xcode 一起工作。(我正在运行:版本 4.3.1 (4E1019) 并在 iPhone 5.0.1 上测试)

I want to fetch the data from the json file into my iphone using a button.

我想使用按钮将 json 文件中的数据提取到我的 iphone 中。

Lets say I get my data from the URL: http://companyurl/jsonfile.json(standard JSON-format)

假设我从 URL 获取数据: http://companyurl/jsonfile.json(标准 JSON 格式)

The jsonfile.json looks somthing like this…;

jsonfile.json 看起来像这样……;

{
  "companylist":   
[
      {
        "company":"Companyname 1",
        "telephone":"1234567890",
        "url":"http:\/\/www.companyname1.com\/",
        "category":"category 1",
        "position":"1",
      },
      {
        "company":"Companyname 2",
        "telephone":"2345678901",
        "url":"http:\/\/www.companyname2.com\/",
        "category":"category 2",
        "position":"2",
      },
      {
        "company":"Companyname 3",
        "telephone":"3456789012",
        "url":"http:\/\/www.companyname3.com\/",
        "category":"category 3",
        "position":"3",
      }
]
}

What do I write in my .h, and my .m file?

我在 .h 和 .m 文件中写了什么?

Thanks for any help! :)

谢谢你的帮助!:)

回答by ilhnctn

NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://your_web_server/your_file...."]];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
                                NSJSONReadingMutableContainers error:&error]; 

NSLog(@"Your JSON Object: %@ Or Error is: %@", response, error);

NOTE: This code works on Xcode 4.2 with iOS 5.01 on simulator and 5.1 on iPad device at the moment

注意:此代码目前适用于模拟器上的 iOS 5.01 和 iPad 设备上的 5.1 Xcode 4.2

回答by CustomCase

Thanks guys. I figured it out. (...and here is what I did:)

谢谢你们。我想到了。(……这就是我所做的:)

In my .m file I added this code:

在我的 .m 文件中,我添加了以下代码:

    - (IBAction)getDataFromJson:(id)sender {
        NSURL *url = [NSURL URLWithString:@"http://yourwebsite.com/jsonfile.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(@"%@", result);
}
}

In my .h file, I added this code:

在我的 .h 文件中,我添加了以下代码:

@interface ViewController : UIViewController
- (IBAction)getDataFromJson:(id)sender;

回答by Jeff Wolski

回答by Matt Rosemeier

Never ever EVER use dataWithContentsOfURL: to get server data this way. It's uncontrollable and can leave your application in an unknown state. You should, at the very minimum, be making all url calls with NSURLRequest. Better yet, if you don't support pre iOS7, use NSURLSession.

永远不要使用 dataWithContentsOfURL: 以这种方式获取服务器数据。它是无法控制的,可能会使您的应用程序处于未知状态。您至少应该使用 NSURLRequest 进行所有 url 调用。更好的是,如果您不支持 iOS7 之前的版本,请使用 NSURLSession。

回答by yogesh yadav

    jsonDict = [[NSDictionary alloc] init];
    data = [[NSArray alloc] init]; 

      url =[NSURLURLWithString:@"Please Type Your URL  "];


 // Parse the JSON data from the given URL
  - (void) parseJSONWithURL:(NSURL *) jsonURL
  {
// Set the queue to the background queue. We will run this on the background thread to keep
// the UI Responsive.
    dispatch_queue_t queue =    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

// Run request on background queue (thread).
      dispatch_async(queue, ^{
      NSError *error = nil;

    // Request the data and store in a string.
      NSString *json = [NSString stringWithContentsOfURL:jsonURL
                                              encoding:NSASCIIStringEncoding
                                                 error:&error];
      if (error == nil){

        // Convert the String into an NSData object.
        NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];

        // Parse that data object using NSJSONSerialization without options.
        jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

        // Parsing success.
        if (error == nil)
        {
            // Go back to the main thread and update the table with the json data.
            // Keeps the user interface responsive.
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                data= [[jsonDict valueForKey:@"Result"] valueForKey:@"data"];
                [jsonTable reloadData];
            });
        }

        // Parsing failed, display error as alert.
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Uh Oh, Parsing Failed." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];

            [alertView show];
        }
    }

    // Request Failed, display error as alert.
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Request Error! Check that you are connected to wifi or 3G/4G with internet access." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];

        [alertView show];
      }
   });
  }


 // Delegate call back for cell at index path.
  - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];

    if (cell == nil)
    {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
}

// Set the main label as the episode name.
   cell.textLabel.text = [[data objectAtIndex:indexPath.row] objectForKey:@"fullname"];




    NSNumber *seasonNum = [[data objectAtIndex:indexPath.row] objectForKey:@"username"];
    NSNumber *episodeNum = [[data objectAtIndex:indexPath.row] objectForKey:@"location"];
    NSMutableString *seasonEpisodeNum = [NSMutableString stringWithFormat:@"username: %@ ", seasonNum];
    [seasonEpisodeNum appendString:[NSMutableString stringWithFormat:@"location: %@", episodeNum]];
    cell.detailTextLabel.text = seasonEpisodeNum;

    return cell;
    }






  -(int) numberOfSectionsInTableView:(UITableView *) tableView
  {
   return 1;
  }


  - (int) tableView:(UITableView *) tableView numberOfRowsInSection:  (NSInteger)section
  {
return [data count];
 }

this code implement .m file

此代码实现 .m 文件

and .h file

和 .h 文件

    {
       NSDictionary *jsonDict;
       IBOutlet UITableView *jsonTable;
       NSArray *data;
       NSURL *url;
    }

回答by Drew C

There isa code example in the form of the Tweeting sample app.

在形式的代码示例啁啾示例应用程序