An iOS framework description: Mknetworkkit

Source: Internet
Author: User
<span id="Label3"></p><p><p>http://blog.csdn.net/kmyhy/article/details/12276287</p></p><p><p>http://blog.csdn.net/mobailwang/article/details/25056959</p></p><p><p></p></p><p><p>ASIHTTPRequest (bencopsey) is a powerful framework for using simple, simple to complex HTTP requests, or for working with rest services such as Amazon S3, Rackspace.</p></p><p><p>unfortunately, Ben had stated on September 21, 2011 that it had ceased developing and supporting the framework (see http://allseeing-i.com/%5Brequest_release%5D; )。</p></p><p><p>Ben recommends a number of alternative frameworks (such as afnetworking, RestKit or lrresty). But the most potential is Mugunth Kumar mknetworkkit. Mugunth has released many high-quality, Open-source Ios/mac code (such as mkstorekit), which is worth recommending a replacement for Ashttprequest: Mknetworkkit. It supports arcs and blocks, is easy to use and extremely efficient.</p></p><p><p>The following is excerpted from Mugunth's own Blog. The original is located in: http://blog.mugunthkumar.com/products/ios-framework-introducing-mknetworkkit.</p></p><p><p></p></p><p><p>Suppose you have a network framework that automatically caches respones for you and automatically remembers your actions when you're offline, what do you think?</p></p><p><p>When You're offline, you can bookmark a tweet or mark a feed as read, and when You're online again, the network framework will automatically perform your actions, all without requiring you to write extra Code. Take a look at my introduction to the Mknetworkkit Framework.</p></p><p><p></p></p><p><p><strong>What is mknetworkkit?</strong></p></p><p><p><strong>Mknetworkkit</strong> is a o-c-written network framework that supports blocks, arcs and is simple to use.</p></p><p><p>Mknetworkkit set ASIHTTPRequest and afnetworking two frames in One. In addition to the excellent features of the integration, there is a new stack of features Added. In particular, it allows you to write code more easily than other frameworks. It keeps you away from the disgusting network code COMPLETELY.</p></p><p><p><strong>Characteristics</strong></p></p><p><p><strong>Ultra-Lightweight Frame</strong></p></p><p><p>The entire framework has only 2 classes and some category METHODS. therefore, It is extremely simple to use.</p></p><p><p><strong>There is only one global queue in the entire program</strong></p></p><p><p>Apps that rely heavily on Internet connections should prioritize the number of concurrent network THREADS. unfortunately, There is no network framework to do this well enough. therefore, Once you do not control the concurrency of the network threads in the program, it is very easy to cause errors.</p></p><p><p>Suppose you want to upload a bunch of pictures to the Server. The vast majority of mobile networks (3G) will not allow you to have more than 2 HTTP concurrent connections to the same IP address. In other words, on a device, you can't get more than 2 HTTP concurrent connections from a 3G Network. For Edge is worse, most cases cannot exceed 1. This limit is much wider (6) compared to a home broadband network (wifi). however, You cannot always use wifi, and you must also consider the connectivity of limited networks (narrowband). More often, idevice devices can be connected to a 3G network, so you can only upload 2 images at a Time. however, The real problem is not slow upload speed, but another situation. When you open a view that attempts to load a thumbnail (a different view), the upload thread is run to the Background. If you don't have control over the number of threads in the upload queue, your thumbnail will load the Timeout. This is not normal. The correct way is to optimize the thumbnail load thread, or let the thread wait until the upload is complete before loading the Thumbnail. This requires you to have only one queue in the entire Program.</p></p><p><p>Mknetworkkit uses a singleton in each of its instances to ensure this. Not that Mknetworkkit is a singleton, but that its shared queue is a Singleton.</p></p><p><p><strong>Display network status indication correctly</strong></p></p><p><p>Many 3rd party frameworks display network status through a "network connection increase/decrease" method callback, and Mknetworkkit automatically displays network status due to the use of a singleton shared Queue. In a shared queue, there is a thread that is KVO to observe the Operationcount property at any Time. So for developers, there is generally no need to worry about the display of network Status.</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>if (object = = _sharednetworkqueue && [keypath isequaltostring:@ "operationcount"]) {</p><p>[uiapplication sharedapplication].networkactivityindicatorvisible = ([_sharednetworkqueue.operations count] < 0 );</p><p>}</p></td> </tr> </tbody> </table><p><p><strong>Automatically change queue size</strong></p></p><p><p>As mentioned earlier, most mobile networks do not allow more than 2 concurrent connections, so your queue size should be set to 2 under 3G Network. Mknetworkkit will handle this automatically for YOU. When the network is out of 3g/edge/gprs, it adjusts the concurrency to 2. When the network is on a WiFi network, it is automatically adjusted to 6. This adjustment can be a great benefit when you load thumbnails from a remote server over a 3G Network.</p></p><p><p><strong>Auto Cache</strong></p></p><p><p>Mknetworkkit can automatically cache all your GET requests. When you initiate the same request again, Mknetworkkit can then call the response cache (if Available) to handler for Processing. of course, It also makes a request to the Server. Once the server data has been obtained, handler is again required to process the newly acquired Data. In other words, you don't have to cache manually. You only need to use:</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>[[mknetworkengine sharedengine] usecache];</p></td> </tr> </tbody> </table><p><p>of course, You can override this method (subclass), customize your cache path and the memory overhead that the cache Consumes.</p></p><p><p><strong>Freeze Network operations</strong></p></p><p><p>Mknetworkkit can "freeze" network operations. In the event that a network operation is "frozen", once the network is disconnected, they are automatically serialized and automatically committed once the device is connected Again. Similar to the Twitter Client's "drafts".</p></p><p><p>When you submit a tweet, if the network is marked as "frozen", Mknetworkkit automatically freezes and stores the Requests. This tweet will therefore be postponed in the Future. The whole process doesn't require you to write a single line of Code. This feature can be used for other operations, such as collecting a tweet or sharing a post from the Goolge reader client, Adding a link to the instapaper, and so On.</p></p><p><p><strong>A similar request performs only one operation</strong></p></p><p><p>When you load thumbnails (for Twitter stream), you end up creating a new request for each actual picture. In fact, the multiple requests you make are the same url. Mknetworkkit is only executed once for each GET request in the Queue. It is not yet possible to cache POST Requests.</p></p><p><p><strong>Picture Cache</strong></p></p><p><p>The Mknetworkkit has a built-in thumbnail cache. You can set the maximum number of cached images in memory and the cache to be saved to the directory as long as several methods are Covered. of course, You can also not overwrite these methods.</p></p><p><p><strong>Performance</strong></p></p><p><p>That is Speed. Mknetworkkit caches are built-in, such as nscache, when a memory warning is found, the data cached into memory is written to the cache directory.</p></p><p><p><strong>Full support for ARC</strong></p></p><p><p>In general, you will only use the new network framework in new Projects. Mknetworkkit doesn't mean giving up on an existing framework (you can, of course, give up, it's a tedious job). For new projects, you always want to use ARC. When you see this article, it is likely that Mknetworkkit will be the only network framework that fully supports ARC. ARC is usually faster than Non-arc Code.</p></p><p><p><strong>Usage</strong></p></p><p><p>ok, I will not "puff". Let us immediately understand if this framework is Used.</p></p><p><p><strong>Add Mknetworkkit</strong></p></p> <ol type="1" start="1"> <ol type="1" start="1"> <li>Drag the Mknetworkkit directory to the project</li> <li>Add the following frames: cfnetwork.framework, systemconfiguration.framework, security.framework and Imageio.framework.</li> <li>Include the MKNetworkKit.h header file in the PCH file</li> <li><span style="color: #ff0000;">For iOS, Remove Nsalert+mknetworkkitadditions.h</span></li> <li><span style="color: #ff0000;">For Mac, Remove Uialertview+mknetworkkitadditions.h</span></li> </ol> </ol><p><p>A total of only 5 core files, really a powerful network development package</p></p><p><p><strong>Class of Mknetworkkit</strong></p></p> <ol type="1" start="1"> <ol type="1" start="1"> <li>Mknetworkoperation</li> <li>Mknetworkengine</li> <li>Some tool classes (Apple's Reachability) and categories</li> </ol> </ol><p><p>I like Simple. Apple has written the most basic and core network Code. The 3rd party framework needs to provide an elegant network queue with a maximum of cache. I don't think the 3rd party framework should be more than 10 classes (whether it's a network or a UIKit or something). Exceeding this number is too bloated. Three20 is an example. Now Sharekit is like this again. Although they are excellent, they are still huge and bloated. ASIHTTPRequest or afnetworking is lighter than RESTKit, jsonkit is lighter than Touchjson (or any touchcode library). This is only my own opinion, but when a Third-party library code exceeds the program source code 1/3, I will not use it.</p></p><p><p>The problem with a bloated framework is that it's hard to understand how it works inside, and it's hard to tailor it to your needs (when you need it). Some of the frameworks I've written (such as mkstorekit, for In-app purchases) are always easy to use, and I think Mknetworkkit should do the Same. For mknetworkkit, all you need to know is the methods exposed in the two classes Mknetworkoperation and Mknetworkengine. Mknetworkoperation is like the asihttprequest class. It is a nsoperation subclass that encapsulates your request and the response class. For each network operation, you need to create a Mknetworkoperation.</p></p><p><p>Mknetworkengine is a Pseudo-singleton class that manages network queues in Programs. It is a pseudo-singleton, that is, for a simple request, you can directly use the method in Mknetworkengine. To make a deep customization, you should subclass it. Each mknetworkengine subclass has its own reachability object that notifies it of reachability notifications from the Server. For different REST servers, you might consider creating a separate mknetworkengine subclass.</p></p><p><p>It is a pseudo-singleton, with each request for its subclasses sharing a unique Queue. You can retain this mknetworkengine in the application delegate, just like Coredata's managedobjectcontext class. When you use mknetworkkit, you create a mknetworkengine subclass that logically groups your network Requests. For example, put all the methods on Yahoo in one class, and all Facebook-related methods are put into another class. Take a look at 3 examples of practical use.</p></p><p><p><strong>Example 1:</strong></p></p><p><p>Create a "yahooengine" to grab the currency exchange rate from the Yahoo finance server.</p></p><p><p><strong>Step 1:</strong> Create the Yahooengine class that inherits from Mknetworkengine. Mknetworkengine is initialized with the host name and the specified header (if any). The header information can be Nil. If you are on your own REST server, you may consider adding a version of the client app or other information (such as the Client's identity).</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>Nsmutabledictionary *headerfields = [nsmutabledictionary dictionary]; [headerfields setvalue:@ "iOS" forkey:@ "x-client-identifier"];</p><p>Self.engine = [[yahooengine alloc] initwithhostname:@ "download.finance.yahoo.com" Customheaderfield s:headerfields];</p></td> </tr> </tbody> </table><p><p></p></p><p><p>Note that Yahoo does not recognize you sending x-client-identifier to it in the header, This example simply demonstrates this feature and</p></p><p><p>Since the ARC code is used, as a developer you need to have (a strong Reference) engine Object.</p></p><p><p>Once you have created a mknetworkengine subclass, reachability is automatically implemented. When your server is suspended due to certain circumstances, the hostname is inaccessible and your request is automatically Frozen. For "freeze", refer to the "freezing operations" section Later.</p></p><p><p><strong>Step 2:</strong> Design engine class (focus on Separation)</p></p><p><p>now, start writing the methods in Yahoo Engine to grab the Exchange Rate. These methods will be called in Viewcontroller. A good design experience is to ensure that url/httpheaders in the engine class are not exposed to the Caller. Your view should not know the URL or related Parameters. That is, you simply pass the currency type and unit of currency to the engine method. The return value of the method may be double, that is, the Exchange rate, and the time to get the Exchange Rate. Because it is an asynchronous operation, you should return these values in the BLOCK. For example:</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>-(mknetworkoperation*) currencyratefor: (nsstring*) sourcecurrency</p><p>Incurrency: (nsstring*) targetcurrency</p><p>Oncompletion: (currencyresponseblock) Completion</p><p>OnError: (errorblock) error;</p></td> </tr> </tbody> </table><p><p>In the parent class mknetworkengine, 3 block types are defined:</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>typedef void (^PROGRESSBLOCK) (double progress);</p><p>typedef void (^RESPONSEBLOCK) (mknetworkoperation* operation);</p><p>typedef void (^ERRORBLOCK) (nserror* error);</p></td> </tr> </tbody> </table><p><p>In yahooengine, we used a new block type:<em>Currencyresponseblock</em>, which returns the Exchange Rate. It is defined as Follows:</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>typedef void (^CURRENCYRESPONSEBLOCK) (double rate);</p></td> </tr> </tbody> </table><p><p>In other formal apps, you should define your own block similar to <em>Currencyresponseblock</em> to return data to Viewcontroller.</p></p><p><p><strong>Step 3:</strong> Process the data<br>Process data, including data type conversions from the data captured from the server (for example, json/xml/plists). This should be done in the ENGINE. Note that do not complete in the Controller. Your Engine should return the data to an array of appropriate model objects or model Objects. Convert Json/xml to model in engine-note that proper separation of concerns should not be known by the view controller for accessing the JSON Node's key. This idea dominates the design of the ENGINE. Many network frameworks do not compel you to obey the separation of concerns, and we do so because we have taken it into consideration for YOU.</p></p><p><p><strong>Step 4:</strong> Implement the method<br>Now let's discuss the implementation details of the Method. To get the exchange rate information from Yahoo, the simplest is to initiate a get Request. The following macro formats the URL string with a pair of specified currencies:</p></p><p><p>WE'LL now discuss the implementationdetails of the method that calculates your currency exchange.</p></p><p><p>Getting currency information from Yahoo,is as simple as making a GET Request.<br>I wrote a macro to format the this URL for a given currency pair.</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>#define Yahoo_url (__c1__, __c2__) [nsstring stringwithformat:@ "d/quotes.csv?e=.csv&amp;f=sl1d1t1&amp;s=%@% @=x ", __c1__, __c2__]</p></td> </tr> </tbody> </table><p><p>The engine class method is written in the following order:</p></p> <ol type="1" start="1"> <ol type="1" start="1"> <li>Prepare URLs based on parameters</li> <li>Create a Mknetworkoperation object</li> <li>Setting method parameters</li> <li>Set completion block and error block for Operation (process Response in Completation block and convert to Model)</li> <li>optionally, Add a progress block (or do this in the view Controller)</li> <li>If operation is a download, set the download stream (usually a file). This step is also optional.</li> <li>When operation finishes, the result is processed and the method block is called, and the data is returned to the Caller.</li> </ol> </ol><p><p>The sample code is as Follows:</p></p><p><p>Mknetworkoperation *op = [selfoperationwithpath:yahoo_url (sourcecurrency, Targetcurrency)</p></p><p><p>Params:nil</p></p><p><p>httpmethod:@ "GET"];</p></p><p><p></p></p><p><p>[op oncompletion:^ (mknetworkoperation*completedoperation)</p></p><p><p>{</p></p><p><p>DLog (@ "%@", [completedoperation responsestring]);</p></p><p><p></p></p><p><p>Do your processing here</p></p><p><p>Completionblock (5.0f);</p></p><p><p></p></p><p><p>}onerror:^ (nserror* Error) {</p></p><p><p></p></p><p><p>Errorblock (error);</p></p><p><p>}];</p></p><p><p></p></p><p><p>[self enqueueoperation:op];</p></p><p><p></p></p><p><p>Return op;</p></p><p><p>The code above formats the URL and creates the Mknetworkoperation. After setting the completion and error blocks, add operation to the queue (through the Enqueueoperation method of the parent Class) and return a operation Reference. therefore, If you call this method in viewdidappear, the operation is canceled in the Viewwilldisappear method. Canceling operation will release operation in order to execute operation for other view in the queue (keep in mind that only 2 operation in the mobile network can be performed simultaneously, and when operation is no longer needed, canceling them can boost the App's Performance and speed).</p></p><p><p>You can also add a progress block in Viewcontroller to refresh the Ui. For example:</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>[self.uploadoperation onuploadprogresschanged:^ (double Progress) {</p><p>DLog (@ "%.2f", progress*100.0);</p><p>Self.uploadProgessBar.progress = progress; }];</p></td> </tr> </tbody> </table><p><p>Mknetworkengine also has a useful way to create operation only with Urls. So the 1th line of code can also be written as:</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>Mknetworkoperation *op = [self operationwithpath:yahoo_url (sourcecurrency, targetcurrency)];</p></td> </tr> </tbody> </table><p><p>Note that the requested URL is automatically added on the host name (as specified when the engine is instantiated).</p></p><p><p></p></p><p><p>There are many practical methods like this mknetworkengine, you can view the header File.</p></p><p><p><strong>Example 2:</strong></p></p><p><p>Upload images to the server (E.G. twitpic).<br>Now let's look at an example of uploading images to a server. To upload a picture, it is obvious that operation can encode multi-part form Data. Mknetworkkit uses a similar asihttprequest Approach.<br>You can submit a file as a multi-part form data in a request very simply by using the Mknetworkoperation addfile:forkey: method.</p></p><p><p>Mknetworkoperation also has a way to submit pictures in a nsdata way. The adddata:forkey: method, which uploads the image to the server in a NSData way. (for example, Pictures captured directly from the camera).</p></p><p><p><strong>Example 3:</strong></p></p><p><p>Download files to a local directory (cache)<br>Using Mknetworkkit to download files from the server and save them to your IPhone's local directory is Simple.</p></p><p><p>You only need to set the Mknetworkoperation Outputstream.</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>[operation Setdownloadstream:[nsoutputstream outputstreamtofileatpath:@ "/users/mugunth/desktop/ Downloadedfile.pdf "append:yes]";</p></td> </tr> </tbody> </table><p><p>You can set multiple OutputStream to a operation and save the same file to several places (for example, one is your cache directory and the other is your working directory).</p></p><p><p><strong>Example 4:</strong></p></p><p><p>Thumbnail image of cached pictures</p></p><p><p>For downloading images, you may need to provide an absolute URL address instead of a path.<br>Mknetworkengine OperationWithURLString:params:httpMethod: method creates a network thread based on an absolute URL address.</p></p><p><p>Mknetworkengine is quite clever. It merges multiple GET requests for the same URL into one, and it notifies all blocks when the operation is Complete. This significantly improves the speed at which image URLs are crawled to render Thumbnails.</p></p><p><p>The subclass Mknetworkengine then overwrites the Image's cache directory and the size of the Cache. If you do not want to customize both, you can directly invoke the method in Mknetworkengine to download the Image. This is what I highly recommend.</p></p><p><p><strong>Cache operation</strong></p></p><p><p>Mknetworkkit all requests are cached by Default. All you need is to open it in your own engine. When a GET request is executed, if the last response is cached, the corresponding completion block is invoked with the cached response (instantaneously). To know if response is cached, you can call the Iscachedresponse method as Follows:</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td> <p> [op oncompletion:^ (mknetworkoperation * Completedoperation)  {</p> <p>           if ([completedoperation Iscachedresponse])  {</p> <p>                DLog (@ "Data from cache"); </p> <p>           }else {</p> <p>                dlog (@ "Data from server"); </p> <p>           } </p> <p>             dlog (@ "%@",  [completedoperation responsestring]); </p> <p>       } </p> <p> onerror:^ (nserror* error)  {</p> <p>              errorblock (error); </p> <p>}]; </p> </td> </tr> </tbody> </table><p><p><strong>Freeze operation</strong></p></p><p><p>One of the most interesting features of Mknetworkkit is its built-in freeze operation Feature. You just have to set the Freeesable property of Operation. There's almost nothing to do!</p></p> <table border="0" cellpadding="0"> <tbody> <tr> <td><p>[op setfreezable:yes];</p></td> </tr> </tbody> </table><p><p>Freezing means that operation is automatically serialized when the network is disconnected and automatically executed after the network is Restored. For example, when you are offline, you can also do a collection of tweets, and then operation automatically resume execution when you go online again.</p></p><p><p>Frozen operation are also persisted to disk when the application enters the Background. It then resumes execution automatically after the application returns to the Foreground.</p></p><p><p><strong>Useful methods in Mknetworkoperation</strong></p></p><p><p>As shown below, Mknetworkoperation exposes a number of useful methods from which you can get response data in various formats:</p></p> <ol type="1" start="1"> <ol type="1" start="1"> <li>ResponseData</li> <li>Responsestring</li> <li>Responsejson (only on IOS 5)</li> <li>Responseimage</li> <li>Responsexml</li> <li>Error</li> </ol> </ol><p><p>These methods are used to get the response data when the operation finishes Executing. If the format is not correct, the method returns Nil. For example, The response data is obviously an HTML format, and you will only get nil with the Responseimage method. Only ResponseData can guarantee that any format is returned correctly, while other methods you must ensure match the corresponding Repsone type.</p></p><p><p><strong>Useful macros</strong></p></p><p><p>DLog and ALOG macros were shamelessly stolen from stackoverflow, I could not find the source Author. If you have written it, please let me know.</p></p><p><p><strong>A little note on GCD</strong></p></p><p><p>Because the network thread is likely to be able to be stopped or prioritized, I decisively give up the efficiency of GCD--GCD is higher than nsoperation, but it does not do This. I recommend that you also do not use GCD-based queues in your network threads.</p></p><p><p>An iOS framework description: Mknetworkkit</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.