我是 ObjC 的新手,正在编写一个简单的 CONSOLE 应用程序来从 web 获取数据并解析或做一些事情。我正在尝试使用 NSURLConnection 但在获取任何数据时遇到问题。我使用 TCPDUMP 来捕获流量,我看到请求甚至没有被发送出去,因此我什至没有在控制台中得到任何结果。我不是想在 mac 上创建一个简单的控制台应用程序,而是创建 ios 应用程序。任何帮助将不胜感激。** 我在这个项目中使用 Xcode v4.2 和 ARC。
主.m:
#import <Foundation/Foundation.h>
#import "HTTPRequest.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
HTTPRequest *http = [[HTTPRequest alloc]init];
[http doMagic ];
}
return 0;
}
HTTPRequest.h:
#import <Foundation/Foundation.h>
@interface HTTPRequest :NSObject <NSURLConnectionDelegate> {
NSMutableData *webData;
NSURLConnection *conn;
}
-(void) doMagic;
@end
HTTPRequest.m:
#import "HTTPRequest.h"
@implementation HTTPRequest
-(void) doMagic {
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
conn = [[NSURLConnection alloc] initWithRequest:req
delegate:self];
if (conn) {
webData = [NSMutableData data];
NSLog(@"DEBUG: %@", [webData length]);
}
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[webData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(@"Succeeded! Received %lu bytes of data",[webData length]);
NSLog(@"DONE. Received Bytes: %lu", [webData length]);
NSString *theData = [[NSString alloc] initWithBytes:[webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
// -prints html received --
NSLog(@"%@", theData);
}
@end