我对 iOS 开发相当陌生,我正在尝试从 URL 获取内容。我正在使用 Apple 教程来使用 NSURLConnection,一切正常,但我没有获取数据。我环顾四周,找不到我的问题的答案。我也在我的项目中使用ARC,也许这会导致问题?
这是我正在使用的代码,从我的头文件开始:
@interface ViewController : UIViewController
@property (nonatomic, retain) NSMutableData *receivedData;
@end
实现文件:
@implementation ViewController
@synthesize receivedData;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"1. viewDidLoad");
// Create the request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// Create the connection with the request and start loading the data
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(@"2. connection succeeded");
receivedData = [NSMutableData data];
} else {
NSLog(@"2. connection failed");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"3. didReceiveResponse");
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"4. Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"4. Succeeded! Received %d bytes of data", [receivedData length]);
}
所有的 NSLog 都在工作,但它一直说 receivedData 有 0 个字节。我找不到我的问题的答案,所以我希望我能找到这个问题的答案。