Tutorial: Asynchronous HTTP client with NSOperationQueue
Introduction
recently here at ELC, we are working on an application that requires a lot of server interaction, which has been a learning experience for managing threading, server load and connectivity. To maintain application performance and agile when you send a large number of applications and aggregate a large dataset, our group had to intelligently manage and prioritize network interactions.
Here NSOperationQueue help. This class is highly dependent on Grand Central Dispatch (GCD) to run NSOperations (in this case, the HTTP requests and JSON SERIALIZATIONS). These operations can be performed in various settings, including simultaneously and asynchronously. In this tutorial I will show you how to make a block-based queue using NSBlockOperation operations, a concrete subclass of NSOperation. You can use this client server class to manage all interactions with the external server. To demonstrate this, our Twitter sample issue for a set of tags and keywords to return the results asynchronously. The sample code is available on GitHub . Let’s get started. Client Server Setup
First, create a class Media Server with a property transaction queue. This class is a singleton server because we want to route all network requests from a single file operation.
files project, you will notice Search View Controller Tags. I set it up to handle the deletion, addition and editing Search tags Twitter. You can find a very simple implementation, with NSUserDefaults to continue their search tags. The main objective of this regulator of view is to prepare a series of requests from the server. Server
talks with NSBlockOperation
Now we are ready to start our business line. In our example, we will search for tweets that contain different keywords, so just need a get method in our class server
Note. Since the blocks are syntactically somewhat hard to read, it may be appropriate to assign typedef parameters of an input block and returns. This also means much more readable to cross the block. In our example, we expect a number of objects tweet, and we should look for errors in the HTTP request and JSON serialization. In MediaServer.h, add:
class = "code"> class = typedef void ( ^ ) ( NSArray * items NSError * wrong) class = "code"> class = - ( ) : ( NSString * ) String Search block : ( FetchBlock 002200; "cor: #) Lock, { * [ transaction block NSBlockOperation blocks with : ^ { NSMutableArray * = [ [ NSMutableArray ] ] , NSError * null , NSHTTPURLResponse # * = null , NSString * = [ String Search stringWithURLEncoding ] , * = [ NSString string with the format : @ = [ : [ : ] #: #] , NSData * = [ NSURLConnection : query response returned : & Error response span style : & ] , NSDictionary * = [ : 0 : & ] span style NSArray * = style = # [ @ ] / / Serialize JSON response Tweet light convenience items to ( NSDictionary * in / "color: =) { Tweet * = [ [ ] ] , [ : #] , } NSLog ( @ " Search "% @"% back in profit . " String, Search, [ count] ) / / return to the main queue, once the request has been processed [ [ NSOperationQueue #] : ^ { if (> ( null , error span style ) , more ( tweetObjects, span style zero ) , } style = #] } ] , / / You can also set the priority function This is useful when flood / / operation with different preferences [ #: ] , [ if addOperation operationQueue ] , #}Let's see how we use this method of server I TweetsViewController viewDidLoad:. . approach, we go our tags search and retrieve each set of tweets Because each transaction sent to our line of business, no need to worry about flooding the server or cause timeouts because of limited bandwidth to do it in viewDidLoad:., add: class = "code"> class = Media Server * = [ #] , ( NSString in ) {# [ server: : ^ ( NSArray * NSError * # wrong) { if ( && == ) { [ items] , NSArray * = [ NSArray array with the object : [ NSSortDescriptor : @ " createdAtDate " No ] ] style = [ : sortDescriptorsArray ] , [ 002200; "cor: #] , [ ] } 002200; "color: #} ]
research Canceling Tweet
In some cases, you may want to stop the activities of its queue, for example, when the user navigates away from a view that displays the contents of various requests servers. this example, when the user hit back " Tags "button, we want to avoid crossing other queries This is as easy as:.
class =" wp_syntax ">
class =" code "> style = # - ( void #) : ( BOOL ) excited # { Media Server * = [ ] , [ [ ] "cor: # 002200] , #}
competition
The only fetchTweetsForSearch: block: do is create a business and submit it to the queue, so back almost immediately The main advantage of this method is that all work within the operating block. occurs in a background queue, leaving the wire free and ensure the UI is responsive. To confirm this works, you can open the profiles of time instruments (a very useful tool for improving UX) and check the queue block running.
In the profiles, you'll see that initWithJSON : , JSONObjectWithData: options: error: and sendSynchronousRequest: return Response: error: ... all running on a worker thread ship, the red wire is not exactly what we want
Conclusion
There you have as a developer you will get the maximum benefit from this server paradigm when you send a large number of URL requests or when the user is on a slow network. If you run into situations where the queue full of desires, remember that you can prioritize their activities, such as
class = "code"> [ : ]Congratulations iCoding
Source Code -! GitHub
http:/ .. ::: / www.icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue / :::
Ditulis oleh Unknown
Rating Blog 5 dari 5
0 komentar:
Posting Komentar