Tutorial: Asynchronous HTTP client with NSOperationQueue

Posted by Unknown Senin, 18 Februari 2013 0 komentar

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.

class = “code”> class = @ interface Media Server: NSObject # @ property ( strong ) NSOperationQueue # * operationQueue, + ( ) sharedMediaServer, @ end dispatch_once uses GCD and recommended by Apple for thread safety.

class = "code"> + ( id ) sharedMediaServer, { static dispatch_once_t symbol once, static = null , # ( & token once, ^ { [ [ [ 002200; "color: #] ] init] = "style 002200; "> } Media Server init, initialize the operation queue and put into operation simultaneously counted. The property maxConcurrentOperationCount can be changed later, though

class = "code"> - ( ID ) init, { in ( ( auto = [ ] ) ) { # = [ [ NSOperationQueue ] ] , = 2 002200; "cor: #} return even }
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.

 </p><p> NSOperation profiled

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 / :::

TERIMA KASIH ATAS KUNJUNGAN SAUDARA
Judul: Tutorial: Asynchronous HTTP client with NSOperationQueue
Ditulis oleh Unknown
Rating Blog 5 dari 5
Semoga artikel ini bermanfaat bagi saudara. Jika ingin mengutip, baik itu sebagian atau keseluruhan dari isi artikel ini harap menyertakan link dofollow ke http://apk-zippy.blogspot.com/2013/02/tutorial-asynchronous-http-client-with.html. Terima kasih sudah singgah membaca artikel ini.

0 komentar:

Posting Komentar

Trik SEO Terbaru support Online Shop Baju Wanita - Original design by Bamz | Copyright of apk zippy.