我是ObjC的新手,并且正在编写一个简单的CONSOLE应用程序,以便从网络获取数据并解析数据,或者使用与之相关的操作。我正在尝试使用NSURLConnection,但在获取任何数据时遇到问题。我使用TCPDUMP来捕获流量,并且我发现请求甚至没有发送出去,因此我甚至没有在控制台中得到任何结果。我不是想在Mac上创建一个简单的控制台应用程序ios应用程序。任何帮助将不胜感激。 **我在这个项目上使用Xcode v4.2和ARC。Objective C和NSURLConnection
的main.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
您可能需要调用'[conn fire];' –
您需要运行循环才能使NSURLConnection工作。 GUI应用程序默认设置了一个运行循环,但命令行工具并非如此。看看'NSRunLoop'。 – omz
Thx omz。我认为你正在做的事情,因为我创造了与iOS完全相同的东西,它工作得很好,但由于某种原因,它不能在控制台应用程序工作,我认为你是正确的NSRunLoop(从我最初的谷歌搜索)。我会看看NSRunLoop并回报。 Thx男人。非常感谢您的帮助。 –