如何创建一个方法并在另一个方法中使用它

时间:2013-02-13 14:22:17

标签: ios objective-c afnetworking

我创建了一个使用AFNetworking并从URL获取JSON的方法。但我无法弄清楚如何在ViewDidLoad中使用它。我得到一个错误或一个空的UITable。

这是我的代码:

@interface QWViewController ()

-(void)loadVideoFromURL:(NSURL *)url;

@end

@interface NSURL()

-(void)loadVideoFromURL:(NSURL *)url;

@end

//我创建的方法:

-(void)loadVideoFromURL:(NSURL *)url {

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // setup AFNetworking stuff
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        // call delegate or processing method on success

        self.myJSON = (NSDictionary *)JSON;

        NSLog(@" json %@", self.myJSON);

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];


    [operation start];

}

//这是ViewWillAppear:

   -(void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    //[super viewDidLoad];



    NSLog(@" video Meta Data %@", self.myJSON);
    // link to the youtube channel or playlist NOTE: JSON and JSONC are not the same. Use JSONC, as far as i recall, its customised for youtube.

    NSString *urlAsString = @"http://gdata.youtube.com/feeds/api/playlists/PL7CF5B0AC3B1EB1D5?v=2&alt=jsonc&max-results=50";

    NSURL *myurl = [NSURL URLWithString:urlAsString];

    self.myJSON = [self loadVideoFromURL:myurl];



        // I am using self.videoMetaData. I am defining it in the .h file as a property. This will let me use it anywhere in this .m file.

        self.videoMetaData = [self.myJSON valueForKeyPath:@"data.items.video"];

        NSLog(@" JSON view will apear %@", self.myJSON);

        // This will have all the sq and hq thumbnails

       // self.allThumbnails = [urlcontent valueForKeyPath:@"data.items.video.thumbnail"];


        // The table need to be reloaded or else we will get an empty table.

        [self.tableView reloadData]; // Must Reload

        // NSLog(@" video Meta Data %@", self.videoMetaData);

}

2 个答案:

答案 0 :(得分:4)

loadVideoFromURL

的返回类型无效

您不能像这样分配值

NSURL *urlcontent = [self loadVideoFromURL:myurl];

除非您将方法loadVideoFromURL的返回类型设为NSURL

因此,您应该像这样调用您的方法,而不是在您的情况下将其分配给urlcontent

[self loadVideoFromURL:myurl];

答案 1 :(得分:0)

 NSURL *urlcontent = [self loadVideoFromURL:myurl];