ios 如何发送异步 URL 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8515667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:52:42  来源:igfitidea点击:

How to send Asynchronous URL Request?

iphoneiosxcodensurlconnectionnsurlrequest

提问by Desmond

I would like to know how do I get a return value 1 or 0 only.... back from an URL request asynchronously.

我想知道如何仅从 URL 请求中获取返回值 1 或 0 异步返回。

currently I do it in this way:

目前我这样做:

NSString *UTCString = [NSString stringWithFormat:@"http://web.blah.net/question/CheckQuestions?utc=%0.f",[lastUTCDate timeIntervalSince1970]];
NSLog(@"UTC String %@",UTCString);
NSURL *updateDataURL = [NSURL URLWithString:UTCString];
NSString *checkValue = [NSString stringWithContentsOfURL:updateDataURL encoding:NSASCIIStringEncoding error:Nil];
NSLog(@"check Value %@",checkValue);

this works, however it is blocking my main thread till I got a reply back from the URL, how do I set it so it will do it in a another thread instead of the main thread ?

这是有效的,但是它会阻塞我的主线程,直到我从 URL 得到回复,我该如何设置它以便它会在另一个线程而不是主线程中执行?

EDIT: ANSWERI end upcalling my function with this, it works well :)

编辑:回答我最终用这个调用了我的函数,它运行良好:)

[self performSelectorInBackground:@selector(shouldCheckForUpdate) withObject:nil];

回答by Adil Soomro

you can use NSURLConnectionclass

你可以使用NSURLConnection

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

and handle its response and errors using its delegate methods.

并使用其委托方法处理其响应和错误。

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

You can find implementation of NSURLConnection

你可以找到 NSURLConnection 的实现

Edit: Although NSURLConnectionis provided by apple is more recommended way of placing URL request. But I found AFNetworkinglibrary very time saving, easy to implement and robust yet simple as third party implementation. You should give it a try.

编辑:虽然NSURLConnection由苹果提供是更推荐的放置 URL 请求的方式。但是我发现AFNetworking库非常节省时间,易于实现,并且像第三方实现一样健壮而简单。你应该试一试。

回答by Maulik

try this :

尝试这个 :

.h:

。H:

NSMutableData *responseData;

.m:

.m:

- (void)load 
{
  NSURL *myURL = [NSURL URLWithString:@"http://www.example.com"];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

  [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
  responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
  [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
  [responseData release];
  [connection release];
  [textView setString:@"Unable to fetch data"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
  NSLog(@"Succeeded! Received %d bytes of data",[responseData
                                                   length]);
  NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
}

回答by Saurabh Passolia

Use NSURLConnectionand make your request. Then you may start synchronous or asynchronous connection with NSURLConnection's methods :

使用NSURLConnection并提出您的要求。然后你可以使用 NSURLConnection 的方法启动同步或异步连接:

Loading Data Synchronously

同步加载数据

+ sendSynchronousRequest:returningResponse:error:

Loading Data Asynchronously

异步加载数据

+ connectionWithRequest:delegate:
– initWithRequest:delegate:
– initWithRequest:delegate:startImmediately:
– start

Check the NSURLConnectionclass in Apple Developer API Reference.

检查NSURLConnectionApple Developer API Reference 中的类。

回答by Jingshao Chen

Shamelessly copy from https://gist.github.com/knmshk/3027474. All credits go to https://gist.github.com/knmshk.

无耻地从https://gist.github.com/knmshk/3027474复制。所有学分转到https://gist.github.com/knmshk

xmlData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:
@"http://forrums.bignerdranch.com/smartfeed.php?"
@"limit=NO_LIMIT&count_limit20&sort_by=standard&"
@"feed_type=RSS2.0&feed_style=COMPACT"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:queue
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                           if (error) {
                               xmlData = nil;
                               NSLog(@"error:%@", error.localizedDescription);
                           }
                           [xmlData appendData:data];
                       }];

回答by Jay Imerman

There is an example in the iOS XCode documentation called LazyTableImages. This does an asynchronous URL as well as asynchronous image load into UITableViewcells displayed on the screen after scrolling stops. Excellent example of protocols, asynchronous data handling, etc.

iOS XCode 文档中有一个名为 LazyTableImages 的示例。这会UITableView在滚动停止后将异步 URL 以及异步图像加载到屏幕上显示的单元格中。协议、异步数据处理等的优秀示例。