IOS-Network (HTTP requests, synchronization requests, asynchronous requests, JSON parsing data)

Source: Internet
Author: User

1 //2 //VIEWCONTROLLER.M3 //ios_0129_http Request4 //5 //Created by Ma C on 16/1/29.6 //copyright©2016 Blog Technology. All rights reserved.7 //8 9 #import "ViewController.h"Ten #import "mbprogresshud+mj.h" One  A @interfaceViewcontroller () -@property (Weak, nonatomic) Iboutlet Uitextfield *Textname; -@property (Weak, nonatomic) Iboutlet Uitextfield *Textpassword; the  --(ibaction) btnlogin; -  - @end +  - @implementationViewcontroller + /* A 1. Common scenarios for sending HTTP requests: at 1> Apple-native - nsurlconnection: Simple to use, most classic, most direct - nsurlsession: More powerful than nsurlconnection - Cfnetwork:nsurl Bottom, pure C language - 2> Third party framework - asihttprequest: "http Terminator", feature and powerful, unfortunately stop updating in afnetworking: Simple to use, provide basic enough common functions, maintainers more - Mknetworkkit: Easy to use, less user-friendly maintainers to 3> Recommendations + in order to improve development efficiency, enterprise development is basically a third-party framework -   the 2. Common Classes * 1>nsurl: Request Address $ 2>nsurlrequest: A Nsurlrequest object represents a request-the included information is:Panax Notoginseng A . A Nsurl object - B. Request method, request header, request body the c. Request timed out + 3>nsmutableurlrequest: A 4>nsurlconnection-Responsible for sending requests, establishing client-server connections the send nsurlrequest data to the server and receive data from the server response +   - 3.NSURLConnection Use steps: $ 1> Creating the Nsurl object and setting the request path $ 2> a Nsurl object to create a Nsurlrequest object, set the request header and the request body - 3> using nsurlconnection to send Nsurlrequest -  */ the  -- (void) Viewdidload {Wuyi [Super Viewdidload]; the      -Self.view.backgroundColor =[Uicolor Grouptableviewbackgroundcolor]; Wu } -- (void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event About { $ [Self.view Endediting:yes]; - } -  -  A-(ibaction) btnlogin { +      theNSString *usernametext =Self.textName.text; -     if(Usernametext.length = =0) { $[Mbprogresshud ShowError:@"Please enter your account number"]; the         return; the     } theSelf.textPassword.secureTextEntry =YES; theNSString *password =Self.textPassword.text; -     if(Password.length = =0) { in[Mbprogresshud ShowError:@"Please enter your password"]; the         return; the     } AboutNSLog (@"sending data to the server"); the      the     /* the Interface Documentation: Define a request interface that describes the server side + 1> request path URL: Which path should the client request - 2> Request Parameters: The data that the client wants to send to the server the 3> Request Result: What the server is going to return to the clientBayi      */ the      the     //Create a Nsurl: request path -NSString *strurl = [NSString stringWithFormat:@"http://localhost:8080/mjserver/login?username=%@&pwd=%@", Usernametext,password]; -Nsurl *url =[Nsurl Urlwithstring:strurl]; the     //Create a request theNsurlrequest *request =[Nsurlrequest Requestwithurl:url]; the  the     //Sync Request - [self sendsyncwithrequest:request]; the     //Asynchronous Request the [self sendasyncwithrequest:request]; the     94 } the //Asynchronous Request the- (void) Sendasyncwithrequest: (Nsurlrequest *) Request the {98Nsoperationqueue *queue =[Nsoperationqueue Mainqueue]; About      -[Nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse * _Nullable response, NSData * _nullable data, Nserror *_nullable Connectionerror) {101         //this block will be automatically called when the request is complete.102         if(Connectionerror | | data = =Nil) {103[Mbprogresshud ShowError:@"request failed"];104             return; the         }106         //parse the JSON data returned by the server107Nsdictionary *dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:nil];108NSString *error = dict[@"Error"];109         if(Error) { the [Mbprogresshud Showerror:error];111         } the         Else{113NSString *success = dict[@"Success"]; the [Mbprogresshud showsuccess:success]; the         } the     }];117 }118 119 //Sync Request -- (void) Sendsyncwithrequest: (Nsurlrequest *) Request121 {122     //send user name and password to server (HTTP protocol)123NSData *data =[nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil];124     /* the JSON126 1>json is a lightweight data format that is typically used for data interaction127 the data returned to the client by the server is generally in JSON format or XML format - Standard JSON appropriate NOTE: Key must be enclosed in double quotation marks.129       the 2> to dig out specific data from JSON to parse the JSON131 JSON OC the {}-----------nsdictonary133 []-----------Nsarray134 ""-----------nsstring135 Digital-----------NSNumber136      137 3>json Parsing Solution138 third-party frameworks: Jsonkit, Sbjson, Touchjson (performance from left to right, worse)139 Apple Native (comes with): Nsjsonserialization (Best performance) $ 4>json data to-->oc object141 + (Nullable ID) Jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: (Nserror *) error;142 5>oc Object-->json data143 + (Nullable NSData *) Datawithjsonobject: (ID) obj options: (nsjsonwritingoptions) opt error: (NSERROR *) error;144      */145     //parse the JSON data returned by the server146Nsdictionary *dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:nil];147NSString *error = dict[@"Error"];148     if(Error) {149 [Mbprogresshud Showerror:error]; Max     }151     Else{ theNSString *success = dict[@"Success"];153 [Mbprogresshud showsuccess:success];154     }155     156 }157 @end

IOS-Network (HTTP requests, synchronization requests, asynchronous requests, JSON parsing data)

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.