如何触发NSURLConnection委托方法?

时间:2013-06-10 14:30:31

标签: iphone ios objective-c

当我加载与此类关联的视图时,我似乎无法调用委托方法..它们都没有触发。我确信这是我忽略的东西,但我不能为我的生活找出原因。

DownloadUpdates.h

#import <UIKit/UIKit.h>

@interface DownloadUpdates : UIViewController

    @property (strong, nonatomic) NSMutableData *responseData;
    @property (strong, nonatomic) NSURLConnection *connection;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

@end

DownloadUpdates.m

为了隐私目的,已删除该网址,但它只是调用将返回JSON数据的API。此URL按预期运行,因此这是代码的问题。

#import "DownloadUpdates.h"

@interface DownloadUpdates ()

@end

@implementation DownloadUpdates

- (void)connection:(NSURLConnection *)_connection didReceiveResponse:(NSURLResponse *)response
{
    _responseData = [[NSMutableData alloc] init];
    NSLog(@"Response received");
}

- (void)connection:(NSURLConnection *)_connection didReceiveData:(NSData *)data
{
    [_responseData appendData:data];
        NSLog(@"Data received");
}

- (void)connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error
{
    NSLog(@"Unable to fetch data");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)_connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[_responseData
                                                   length]);
//    NSString *txt = [[NSString alloc] initWithData:_responseData encoding: NSASCIIStringEncoding];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSURL *myURL = [NSURL URLWithString:@"URL HERE"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

    _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

我很感激您提供的任何帮助/建议。

2 个答案:

答案 0 :(得分:2)

使用属性应用强修饰符:

self.responsedata = [[NSMutableData alloc] init];
(.....)
self.connection = [[NSURLConnection alloc] initWithRequest: ....etc...

答案 1 :(得分:0)

我建议在NSLog中添加viewDidLoad或断点,以确保完全调用它。例如,如果您忽略将DownloadUpdates指定为故事板场景的类,则可能会发生这种情况。