IOS webserviceframework Network Service Framework Shallow solution

Source: Internet
Author: User

Unconsciously after graduation also worked for almost half a year, and I always feel that if you do not write something, leaving some traces, I am almost forgotten. From the touch of iOS to the beginning of a little more than a year, I would like to see what I think of some of the skills to share, but their own development experience is not mature, today thick a thick skin, write their first blog, I think as long as not fraught, even if I win it. Let's get to the bottom--build the Web business request framework for iOS.

Web services are almost always a must for every successful app, open your phone and you'll find that the number of apps that don't have to be networked in the 10 can count, even if it's an app like a beauty camera with unique technology in the market, at least the sharing feature. Let me start with a brief review and literacy.

Apple defines the Nsconnection class to handle network requests specifically, and there are two uses for this class to meet the needs of developers.

Usage one, synchronous request

NSURLConnection.h

@interface nsurlconnection (nsurlconnectionsynchronousloading)

  + (NSData *) Sendsynchronousrequest: (nsurlrequest *) Request Returningresponse: (Nsurlresponse *) Response error: ( Nserror * *) error;

@end

// **.M nsmutableurlrequest* request =*data = [nsurlconnection sendsynchronousrequest:request Returningresponse : Response Error:error];

This usage is less used because he is unable to capture the contents of the transfer process and needs to be used in a child thread, otherwise it will be stuck in the UI drawing of the main thread until Sendsynchronousrequest returns data, but wins in a simple, easy-to-use, at-a-glance.

Usage two, asynchronous request

NSURLConnection.h

@interface nsurlconnection: nsobject

Delegate:(ID)delegate  startimmediately: (BOOL) startimmediately; -(void) Scheduleinrunloop: (Nsrunloop *) Arunloop Formode: (NSString *) mode; -(void) start;
@end
**.m
nsmutableurlrequest* request =delegateStartimmediately:no

[Connection start];

Compared to the first usage, the second kind of suddenly let people foggy, especially nsrunloop more questions, in addition, the above code is just the beginning of the request section, the data receiving part of the code has not been posted.

The attentive person noticed that in the. m file, the nsconnection was initialized with a delegate, and yes, the data is handled by Nsurlconnectiondatadelegate callbacks.

NSURLConnection.h
@protocol Nsurlconnectiondatadelegate <NSURLConnectionDelegate>@optional
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data;
-(void) connectiondidfinishloading: (nsurlconnection *) connection; @end

In order not to let other functions disturb everyone's implementation, here I only post the functions related to this article, literally everyone can know this their role, Didreceivedata will carry the requested data multiple callback, didfinishloading is called at the end of the request, There is also a didfailwitherror in the request failed is called, only good he is dad nsurlconnectiondelegate content.

Here we go back to the second usage of the. m file, which involves the execution mechanism of the runloop, and I'll just explain why this is set up here.

Runloop has five modes of operation, here I only say three kinds:

1,nsdefaultrunloopmode: The default mode of operation, except for Nsconnection object events;

2,uitrackingrunloopmode: Used to track touch event triggering patterns (such as uiscrollview up and down scrolling), the main thread is set to this mode when the touch event is triggered;

3,nsrunloopcommonmodes: is a set of commonly used patterns, simple to be a collection of patterns, since it is a collection, of course, including the above two modes.

By default Nsurlconnection,nstimer are running 1 mode, then the problem comes, if the user brushes the screen at this time to switch to mode 2, and then just have data request down, then tragedy, Didreceivedata will not callback. (if nstimer involves sophisticated data calculations, it is also important to note that the solution is to replace it with Nsrunloopcommonmodes.)

The famous sdwebimage in the network asynchronous request picture also uses the second method, the person thinks this method is quite efficient, does not create the new thread the case, relies on the Runloop to listen the network request data, if the schoolmates are still a bit messy, Try replacing the nsurlconnection with Nstimer so that the principle is similar.

And here's a little bit of nsconnection. When initializing, note startimmediately: cannot be set to Yes, if you set to Yes, after setting Runloopmode is not valid.

now understand the most efficient solution for network requests (personally think ...) ), there is no feeling these agents what is very cumbersome, and an app can not only have a network request interface, this time we need a manager role, we temporarily named it as Httpmanager. A manager leads a group of connection, and when you find that the problem comes again, connection looks the same from the outside, there is nothing to mark, so we made him a sub-class myurlconnection and add one more tag field to identify each other. :

With the tag, tag with what to reload it, the only requirement for tag is not to repeat, here I directly use the URL to do tag, because unless the demand, no side URL duplicate request is really not necessary.

In the Didreceivadata, _datatagmap with the data according to tag, append;

In Sendhttprequestwithurl, first check whether the _connectiontagmap already has the object with the URL as key, there is the request, this request can be discarded. There is no new myurlconnection and URL as tag, and finally the URL is key, MyConnection is the value filled in _connectiontagmap;

In didfinishloading, according to the tag value of Connect, the corresponding connection is presented from the _datatagmap and sent to the corresponding model layer processing, and from _datatagmap and _ Connectiontagmap remove the corresponding item;

It sounds simple, actually, it's simple ... Here to send to the model layer may be some students have confused, what is called hair? It is noted that the front _connectiontagmap if there is a duplicate direct discard that is return, so this requires Httpmanager and the class to interact with must be low-coupling, so the meaning of this refers to the use of notification

object: Self userinfo:info];

Info is actually a nsdictionary, inside you want to pretend what to pretend, used to know.

Come here today, originally wanted to write two kinds of request framework comparison, the results only write a only one half, had to next weekend to fill the corresponding network business model layer and another request framework.

IOS webserviceframework Network Service Framework Shallow solution

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.