IOS 14: simple use of asihttprequest and sbjson on the Internet

Source: Internet
Author: User

The current learning is basically different from those tutorials,

Code was officially written last week.

My colleague's UI was faster, so I had to write about network communication, data source model design, and encryption and decryption.

This section briefly describes common third-party Network Libraries and the simple use of JSON Data Protocol formats.

First, introduce the article about the use with the highest click rate on the Internet (the source text is unknown, haha)

Introduction and usage of asihttprequest class library

I just want to briefly describe the most basic part that will be used in general projects. Some things are familiar with them when they are used. If you do not remember so many things at the beginning, you will forget them slowly without practice,

I prefer to look at it for a while. It is okay to create an INDEX DIRECTORY in my mind. We can check the information if we have an index.

First, prepare some download and addition of asihttprequest.

1. I am from GitHub, address https://github.com/pokeb/asi-http-request/

2. Drag the source file to the project and add cfnetwork. Framework,. Framework, mobilecoreservices. Framework, CoreGraphics. Framework, and libz.1.2.3.dylib. All of the above articles are described.

Then let's look at the next simplest asynchronous request.

Contains a URL, a request, and a delegate.

@ Implementation nlnethelper + (void) startrequeswithcontent :( nsobject *) model delegte: delegte {// Step 1: Based on the code, it is determined that the Buddha needs 3DES encryption nsstring * code = [model getmethidcode] nslog (@ "code is !!!!!! % @ ", Code); If (code = @" 10000 ") {}// Step 2: assemble head and body into jsonstring nlhead * head = [[nlhead alloc] init]; // head // nsstring * urlstring = [nsstring stringwithformat: @ "% @. do ", baseurl, Code]; nsurl * url = [nsurl urlwithstring: @" http://www.baidu.com "]; asihttprequest * request = [asihttprequest requestwithurl: url]; [Request setpostbody: Nil]; [Request setdelegate: delegte]; [Request startasynchronous]; // step1. model resolution}

The code is copied directly to the test class in the project, mainly in the following 4-5 sentences.

In Android coding, we tend to encapsulate our network processing classes together.

However, I saw a lot of demos in iOS and found that request parameter processing and request and response processing are all processed in viewcontroller ~

It seems much more convenient at a Glance. You don't need to define some classes similar to bean types to manage them. We need to set some attribute values for processing at the network layer as request parameters,

Instead, they are assembled manually.

Because this is the first project, I do not know that IOS has such a habit that the viewcontroller class basically processes all the logical operations on the current page ~ Because I have seen a project of our outsourcing version.

A viewcontroller has 2, 3 million lines of code ~~

Well, I mean you can write a netmanager, parsehelper, and so on.

In Android, asynchronous operations are generally processed by sub-threads and handler.

IOS is not currently exposed to multithreading. An asynchronous request uses the proxy method to return an error when or when the request is returned.

As we all know the concept of Asynchronization, the straightforward point is that mainthread creates a new subthread. After the sub-thread completes processing, it uses the so-called handler mechanism to notify the main thread,

Or a typical callback function. But some of the proxies and protocols and interfaces are formal. Isn't that true?

@optional// These are the default delegate methods for request status// You can use different ones by setting didStartSelector / didFinishSelector / didFailSelector- (void)requestStarted:(ASIHTTPRequest *)request;- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL;- (void)requestFinished:(ASIHTTPRequest *)request;- (void)requestFailed:(ASIHTTPRequest *)request;- (void)requestRedirected:(ASIHTTPRequest *)request;// When a delegate implements this method, it is expected to process all incoming data itself// This means that responseData / responseString / downloadDestinationPath etc are ignored// You can have the request call a different method by setting didReceiveDataSelector- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;// If a delegate implements one of these, it will be asked to supply credentials when none are available// The delegate can then either restart the request ([request retryUsingSuppliedCredentials]) once credentials have been set// or cancel it ([request cancelAuthentication])- (void)authenticationNeededForRequest:(ASIHTTPRequest *)request;- (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request;

The above are all optional methods. You can see what you mean.

All right, the above are only some of the functions in asihttprequest. Basically, we can solve most of the functions in general network applications.

Ii. sbjson usage

Although we can see that sdk5.0 and above have integrated the JSON Parsing Library. At the same time, it seems that the performance is high, but our current application may be compatible with versions earlier than 5.0.

All of these require us to look at them objectively and then obtain them subjectively.

Sbjson is the same as a third-party package.

1. https://github.com/stig/json-framework

We all know that the JSON format is key value.

To put it bluntly, the JSON format is a string with features.

We assemble the data we want into a bottom-layer jump to the server, and then the server returns the data that is the same as this. We need to parse the data and extract the content.

We all know from Java that the traversal of map is actually in it.

Similarly, in iOS, we need to define a dictionary first, then store the data to be passed in key-value pairs, and then call the JSON parser to generate jsonstring.

Likewise, there will be deserialization.

[Dictionary jsonrepresentation]; The dictionary generates a jsonstring.

Nsmutabledictionary * DIC = [jsonstring jsonvalue]; Convert jsonstring to Dictionary

In fact, Java encapsulation is more perfect than iOS. Can directly operate JavaBean-"jsonstring.

I used reflection and checked it later. It seems that IOS also has reflection ~

Why is bean> jsonstring.

Because, for example, for a user login communication, we will design a loginbean that contains two fields: username and password, followed by the setter and getter methods.

Of course, you don't need bean. You can directly set name and password in viewcotroller as in DIC, because I have read several demo versions like this ~, This is even true for the project we outsourced.

Okay. In simple terms.

Data conversion. If a custom class similar to bean is used, bean-> dic-> jsonstring. The same is true for anti-resolution.

So my processing is:

-(Nsstring *) bean2jsonstring {nsmutabledictionary * dictionary = [nsdictionary dictionarywithobjectsandkeys: partnercode, @ "partnercode", version, @ "version", Prov, @ "prov", mobile, @ "moblie", methodid, @ "methodid", userid, @ "useid", [nsdictionary dictionarywithobjectsandkeys: posttime, @ "posttime", md5sign, @ "md5sign", nil], @ "other", nil]; return [dictionary jsonrepresentation];}-(void) jsonstring2bean :( nsstring *) jsonstring {nsmutabledictionary * DIC = [jsonstring jsonvalue]; nsstring * partnercodestring = [nsstring stringwithformat: @ "modified % @", [DIC objectforkey: @ "partnercode"]; [self setpartnercode: partnercodestring];}

This method is in bean. I think it is not convenient to use JSON in Android. If you throw a standard bean object, you will be given a jsonstring.

In fact, it is also very simple two pieces of content, just done, record. Next, we are going to call encryption to share and learn from it.

Related Article

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.