gpt4 book ai didi

iphone - 如何让 NSURLConnection 委托(delegate)方法触发?

转载 作者:行者123 更新时间:2023-11-29 10:58:47 24 4
gpt4 key购买 nike

当我加载与此类关联的 View 时,我似乎无法调用委托(delegate)方法。它们都没有触发。我敢肯定这是我忽略的事情,但我终生无法弄清楚原因。

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

如果您能提供任何帮助/建议,我将不胜感激。

最佳答案

使用属性应用强修饰符:

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

关于iphone - 如何让 NSURLConnection 委托(delegate)方法触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com