Objective-C:线程中的服务器请求(如 Android 中的 AsyncTask)

发布于 2024-10-04 02:02:00 字数 362 浏览 3 评论 0原文

我想发起一个服务器请求,你可以取消。

我的想法是在线程中启动请求,以便用户界面不会冻结。因此,您可以通过单击“取消”按钮来终止包括请求在内的整个线程。

对于 Android,它可以工作:服务器请求在“AsyncTask”中启动,在“onReturn()”方法中,我可以在服务器请求完成后立即做出反应。

我如何在 iOS 上使用 Objective-C 来实现这一点? 我的第一次尝试是“NSInitationOperation”。您可以取消操作,但是当请求完成且结果可用时,很难处理。我认为 NSIncationOperation 不是我的问题的解决方案。

你会推荐给我吗? NSThread 对我来说是正确的选择吗?

非常感谢!

I would like to start a server request, you can cancel.

My idea is to start the request in a thread so that the user interface does not freeze. So you can kill the whole thread including the request with a click on a "Cancel"-button.

With Android it works: the server request gets started in a "AsyncTask" and in the "onReturn()"-method I can react as soon as the server request finish.

How can I implement this using Objective-C on iOS?
My first attempt was a "NSInvocationOperation". You can cancel the operation, but it's difficult to handle when a request is completed and results are available. I think NSInvocationOperation is not the solution for my issue.

The would you recommend to me? Is NSThread the right choice for me?

Thank you very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一杯敬自由 2024-10-11 02:02:00

注意!

这个非常古老的答案现在仅用于历史目的。

精彩的 ASIHttpRequest 库已不复存在;现在的技术已经完全不同了。


使用 ASIHttpRequest 来做到这一点非常简单。

(异步是如此简单,您没有理由非异步地执行它。)

以下是一些可能帮助您入门的粗略摘录。

...
ASIFormDataRequest *request;
...
NSURL *url = [NSURL URLWithString:@"https://blah.blah/blah.cgi?blah"];
request = [ASIFormDataRequest requestWithURL:url];

[request setPostValue:@"fred" forKey:@"username"];
[request setPostValue:@"flint" forKey:@"passie"];
[request setPostValue:@"stone" forKey:@"town"];

// send up data...
[request setData:[NSData dataWithBytes:blah length:blah] forKey:@"thefile"];

// or perhaps something like...
[request setData:imageData withFileName:@"blah.png"
        andContentType:@"image/jpeg" forKey:@"photoimage"];

[request setDelegate:self];
[request setDidFinishSelector:@selector(postingDone:)];
[request setDidFailSelector:@selector(postingDoneProblem:)];
[request startAsynchronous];
...

-(void) postingDone:(ASIHTTPRequest *)request
    {
    // it worked
    }
-(void) postingDoneProblem:(ASIHTTPRequest *)request
    {
    // failed
    }

实在是再简单不过了。您基本上只需键入字段和值即可。

根据您的问题,以下是取消“进行中”请求的方法...只需将委托设置为 nil,然后“取消”它即可。

  [myRequest setDelegate:nil];
  [myRequest cancel];
  [myRequest release];

ASIHttpRequest 是“奇迹库”。如果您是 iOS 新手,ASIHttpRequest 就是最常用的第三方库。本质上,300,000 个 iPhone 应用程序中的每个 iPhone 应用程序都使用它。

如果可能的话,一定要给这个人捐几块钱——如果他停止支持那个库,100,000 名 iPhone 程序员就会被烦死!

该文档很简单,孩子可以理解它:
http://allseeing-i.com/ASIHTTPRequest/How-to-use
“创建异步请求”

它可能(几乎可以肯定)是任何平台上最简单的网络库。做你所描述的事情是微不足道的,快乐。享受。

Note!

This extremely old answer is now here only for historic purposes.

The wonderful ASIHttpRequest library no longer exists; technology is totally different now.


It is unbelievably simple to do this with ASIHttpRequest.

(Asynchronous is so simple, there is no reason you would ever do it not-asynchronously.)

Here are some rough extracts that might get you started.

...
ASIFormDataRequest *request;
...
NSURL *url = [NSURL URLWithString:@"https://blah.blah/blah.cgi?blah"];
request = [ASIFormDataRequest requestWithURL:url];

[request setPostValue:@"fred" forKey:@"username"];
[request setPostValue:@"flint" forKey:@"passie"];
[request setPostValue:@"stone" forKey:@"town"];

// send up data...
[request setData:[NSData dataWithBytes:blah length:blah] forKey:@"thefile"];

// or perhaps something like...
[request setData:imageData withFileName:@"blah.png"
        andContentType:@"image/jpeg" forKey:@"photoimage"];

[request setDelegate:self];
[request setDidFinishSelector:@selector(postingDone:)];
[request setDidFailSelector:@selector(postingDoneProblem:)];
[request startAsynchronous];
...

-(void) postingDone:(ASIHTTPRequest *)request
    {
    // it worked
    }
-(void) postingDoneProblem:(ASIHTTPRequest *)request
    {
    // failed
    }

Couldn't really be any easier. You're basically just typing out the fields and values.

Per your question, here is how you cancel an "in-flight" request... just set the delegate to nil and then "cancel" it.

  [myRequest setDelegate:nil];
  [myRequest cancel];
  [myRequest release];

ASIHttpRequest is the "miracle library". If you are new to iOS, ASIHttpRequest is simply THE most used 3rd party library. Essentially, every single iPhone app of the 300,000 iPhone apps uses it.

If at all possible BE SURE to donate a few bucks to the guy -- if he stops supporting that library, 100,000 iPhone programmers are buggered!

the documentation is trivial, a child can follow it:
http://allseeing-i.com/ASIHTTPRequest/How-to-use
"Creating an asynchronous request"

it is probably - almost certainly - the most amazingly simple networking library on any platform. It is trivial to do what you describe, happily. Enjoy.

笑脸一如从前 2024-10-11 02:02:00

NSURLConnection 默认是异步的,当连接建立、数据接收或整个请求完成时,支持取消和委托方法。

此外,数据传输在后台进行,以便 UI 保持响应。

NSURLConnection is async by default and supports cancelation as well as delegate methods when connection has been established, data has been received or whole request has been completed.

Also data transfer takes place in background so that UI stays responsive.

清泪尽 2024-10-11 02:02:00

Cocoa 的内置异步网络代码不是基于线程的,而是与运行循环事件一起工作,但结果(异步连接)是相同的。

使用 +[NSURLConnection connectionWithRequest:delegate:] 创建一个 NSURLConnection。您设置的代理将收到有关连接进度的通知,并可以随时使用 -[NSURLConnection cancel] 取消连接。

Cocoa's built-in async networking code is not thread-based but works with run loop events, but the result (asynchronous connections) is the same.

Create an NSURLConnection with +[NSURLConnection connectionWithRequest:delegate:]. The delegate you set will be informed about the progress of the connection and can cancel it anytime with -[NSURLConnection cancel].

緦唸λ蓇 2024-10-11 02:02:00

查看 ASIHTTPRequest,特别是 ASINetworkQueue 子类,其描述为:

ASI网络队列

NSOperationQueue 的子类
可用于跟踪进度
多个请求。

我只使用 ASIHTTPRequest 将单个同步请求直接下载到磁盘,这很容易实现,但我听说过使用队列同时管理多个异步服务器请求的良好报告。

Check out ASIHTTPRequest, specifically, the ASINetworkQueue subclass, which is described as:

ASINetworkQueue

A subclass of NSOperationQueue that
may be used to track progress across
multiple requests.

I've only used ASIHTTPRequest for a single synchronous request to download directly to disk, which was easy to implement, but I've heard good reports of using queues to manage multiple asynchronous server requests at once.

神经暖 2024-10-11 02:02:00

关于使用 +[NSURLConnection connectionWithRequest:delegate:] 的建议需要注意的一件事是,从 iOS 4 开始,它只能从主线程调用。

请参阅 http://blog.mugunthkumar.com/coding/ios4-issue-nsurlconnection-and-nsoperation/ 有关如何处理此问题的示例。

One thing to note on the recommendations to use +[NSURLConnection connectionWithRequest:delegate:] is that it should only be called from the main thread as of iOS 4.

see http://blog.mugunthkumar.com/coding/ios4-issue-nsurlconnection-and-nsoperation/ for an example of how to deal with this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文