1

当我加载与此类关联的视图时,我似乎无法调用委托方法。它们都没有触发。我确定这是我忽略的东西,但我终其一生都无法弄清楚原因。

下载更新.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

下载更新.m

出于隐私目的,该 URL 已被删除,但它只是调用将返回 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

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

4

2 回答 2

2

使用属性应用强修饰符:

self.responsedata = [[NSMutableData alloc] init];
(.....)
self.connection = [[NSURLConnection alloc] initWithRequest: ....etc...
于 2013-06-10T14:46:32.050 回答
0

我建议放置一个NSLog或断点viewDidLoad以确保它被调用。例如,如果您忽略DownloadUpdates为情节提要场景指定类,则可能会发生这种情况。

于 2013-06-10T16:58:22.170 回答