gpt4 book ai didi

ios - Objective C 中的 NSURL 问题

转载 作者:行者123 更新时间:2023-12-01 17:56:55 24 4
gpt4 key购买 nike

我正在尝试执行异步 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com