简体   繁体   中英

Replacing NSURLConnection with AFNetworking

I have been tasked with replacing all NSURLConnection code with AFNetworking code. I am not terribly familiar with either, one thing that puzzles me is how to replace this line:

self.urlConnection = [[NSURLConnection alloc] initWithRequest:self.urlRequest delegate:self startImmediately:true];

I have tried this:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:self.urlRequest];

but AFHTTPRequestOperation has no delegate property. Is there an equivalent in AFNetworking that will call a delegate for NSURLConnectionDelegate methods?

AFNetworking倾向于基于块的方法,因此您可以使用setCompletionBlockWithSuccess:failure:提供块来处理成功接收的数据或失败错误。

AFNetworking won't use your old NSURLConnectionDataDelegate and NSURLConnectionDelegate methods. It replaces a lot of that detailed delegate-based code with something far simpler, a block-based interface. You'll likely be ripping out a lot of the existing code that builds your urlRequest object as well as much of the delegate methods you have. The whole idea of AFNetworking is to get you out of the gory details of that sort of code.

Having said that, you really shouldn't try to replace NSURLConnection code with AFNetworking without a little more familiarity on AFNetworking, at the very least. I'd suggest going through the AFNetworking examples found on their README page, perhaps going through a few AFNetworking tutorials, too (just google it and you should find many).

I would suggest going through your existing NSURLConnection code, making sure you understand what it's trying to do at a high level (eg GET vs POST , JSON vs x-www-form-urlencoded requests, etc.), and then take a crack at replacing it with AFNetworking. We're happy to help if you do a little research and try it yourself. And, it's quite possible that you probably won't even need our help once you see how easy AFNetworking really is. But you need to do a little research and give it a go first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM