如何发送异步 URL 请求? [英] How to send Asynchronous URL Request?

查看:20
本文介绍了如何发送异步 URL 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

目前我是这样做的:

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);

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

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 ?

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

ANSWER I end upcalling my function with this, it works well :)

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

推荐答案

你可以使用 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 

你可以找到 NSURLConnection 的实现

You can find implementation of NSURLConnection

虽然 NSURLConnection 是由苹果提供的,但更推荐的方式是放置 URL 请求.但我发现 AFNetworking 库非常省时、易于实现、健壮又简单作为第三方实现.你应该试一试.

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

这篇关于如何发送异步 URL 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆