【发布时间】:2013-09-16 19:00:40
【问题描述】:
我一般是编程新手,所以请原谅我的无知。如果有人能指出我正确的方向,将不胜感激。
我遵循了 AFNetworking (http://www.raywenderlich.com/30445/afnetworking-crash-course) 的本教程,并在我自己的项目中使用它来解析来自网络的 JSON。
我还没有弄清楚如何将这些数据传输到不同的 UIViewController。我已经看到Passing Data between View Controllers 和其他相关问题无济于事。
我尝试过使用 Delegates&Protocols/Singletons/GlobalVariables/ReferenceClasses,当我 NSLog 的值始终为 NULL 时,我可以让它们用于其他非 JSON 相关材料。 (JSON 数据也会发生变化,我在某处读到其中一些选项是不可变的)
在我看来,本教程使用自定义 NSDictionary 类来存储 JSON 数据并使用 prepareForSegue 传递它:但据我所知,这是仅 Storyboard 的方法。我正在使用笔尖文件。我应该将整个项目切换到 Storyboard 风格,还是有办法使用 Nibs/Xibs 做到这一点?
感谢您抽出宝贵时间阅读本文。我最不想做的事情就是用一个问题来麻烦你,但我已经被困了一段时间了。
编辑:我已经在执行请求的 ViewController 上检索到 JSON 数据,但它不会转移到其他 ViewController,我觉得在每个 ViewController 上请求 JSON 数据是不好的做法我需要它的新控制器。
EDIT2这是一些代码(如果你愿意,我可以发布更多)
-(void)jsonData {
NSLog(@"Loading JSON...");
NSURL *url = [NSURL URLWithString:@"http://fillerCode.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"station",@"1",@"previous_song", nil];
NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/scripts/MoreFillerCode" parameters:params];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest: request
// JSON SUCCESS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Getting Next Song...");
self.get_next_song = (NSDictionary *)JSON;
RightViewController *rightViewController = [[RightViewController alloc] init];
rightViewController.get_next_song = self.get_next_song;
[self updateViewStuff];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Data"
message:[NSString stringWithFormat:@"%@",error]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[av show];
NSLog(@"Operation Failed");
}];
[operation start];
NSLog(@"JSON Operation Started");
}
【问题讨论】:
-
你确定你得到的 JSON 响应是有效的/非空的吗?
-
是的,JSON 响应在 ViewController 上工作,我在其上执行 AFJSONRequestOperation,但仅此而已。抱歉,我没有澄清这一点。我可以在那个 ViewController 上拥有所有从网络上提取的图像、标签和音乐。
-
如果您发布相关的 AFNetworking 代码会有所帮助。
-
在
self.get_next_song = (NSDictionary *)JSON;行之后,添加assert(self.get_next_song);,然后运行您的应用程序,看看它是否崩溃。如果它在那条线上崩溃,则意味着您的数据为零。如果没有,我们将不得不调查其他事情。 -
另外,1RightViewController *rightViewController1 之后好像就没有用了,在块退出后会被销毁。所以无论 1[self updateViewStuff]1 做什么,它都与那个视图控制器无关。
标签: ios objective-c json nsdictionary afnetworking