ios - Objective C 中的 NSURL 问题

标签 ios objective-c

我正在尝试执行异步 http 请求。但回调日志不起作用。请分析代码并建议我这个问题的原因。我在很多地方都看到过此类示例。但在这里我从一个主函数调用它。

@interface HTTP : NSObject

@property (nonatomic,retain) NSMutableData *receivedData;

- (void) get : (NSString *) urlString;

@end



@implementation HTTP

@synthesize receivedData;


- (void)get: (NSString *)urlString {

NSLog ( @"GET: %@", urlString );

self.receivedData = [[NSMutableData alloc] init];

NSURLRequest *request = [[NSURLRequest alloc]
                         initWithURL: [NSURL    URLWithString:urlString]
                         cachePolicy:  NSURLRequestReloadIgnoringLocalCacheData
                         timeoutInterval: 10
                         ];

NSURLConnection *connection = [[NSURLConnection alloc]
                               initWithRequest:request
                               delegate:self
                               startImmediately:YES];

[connection start];





}




- (void)connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Response recieved");
}

- (void)connection:(NSURLConnection*) connection didReceiveData:(NSData *)data
{
NSLog(@"Data recieved");    

NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

[receivedData appendData:responseString];



}



@end




int main(const int c , char *arg[]){

HTTP *http = [[HTTP alloc] init];

[http get:@"http://www.apple.com"];

return 0;
}

最佳答案

您的程序没有“运行循环”,因此它会立即终止

[http get:@"http://www.apple.com"];

在调用任何委托(delegate)函数之前已返回。 (注意 NSURLConnection 异步工作。)

如果这是一个独立的 OS X 应用程序,您可以执行以下操作:
int main(const int c , char *arg[]){

    HTTP *http = [[HTTP alloc] init];

    [http get:@"http://www.apple.com"];

    NSRunLoop *theRL = [NSRunLoop currentRunLoop];
    while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

    return 0;
}

在哪里 shouldKeepRunning是一个(全局) bool 变量,最初是 YES , 并设置为 NO
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    shouldKeepRunning = NO;
}

以及 connection:didFailWithError: .或者您添加一个 bool 属性 loading给您的HTTP类(class)。

如果这是针对 iOS 应用程序或 OS X Cocoa 应用程序,那么您已经有了一个运行循环,无需添加您自己的。

关于ios - Objective C 中的 NSURL 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15812783/

相关文章:

ios - 无法更改自定义 View 的框架大小

ios - 代码 : changing view size depending on screen size

iphone - 我如何从 iphone 中删除 coredata

ios - 无法将新创建的 cocoa pod 添加到私有(private) pod 规范

iOS导航栏总是空的

objective-c - 重新聚焦时重新加载 NSTableView

objective-c - 如何从 apns 获取设备 token 到设备?

ios - iPad 设备上的按钮图像错误,但模拟器中没有

iOS swift 3 : NetworkIndicator won't show itself upon connecting to server

ios - 安装pod文件后改了工程名,没想到遇到如下问题