我是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男人。非常感謝您的幫助。 –