Web Requests for iOS

Source: Internet
Author: User

The more secure HTTPS security hypertext protocol is followed in iOS, and the following settings are required to access Web pages that follow the HTTP protocol:

Add Code <key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

Copied to

The path;

or add the following fields in the Info.plist file

The request is divided into get and post two ways, each of which contains both synchronous and asynchronous forms, synchronization is the application of the Dayton phenomenon, this is only the form of asynchronous.

Before iOS7 use Nsurlconnection to make a request for the network, iOS7 the previous method is refactored and changed to Nsurlsession. First introduce the nsurlconnection, although it is refactored but can still be run:

#pragma mark- nsurlconnection- Asynchronous GET request
-(Ibaction) Getasynchronousrequest: (UIButton *) Sender {
1. Create a URL
Nsurl *url = [Nsurl Urlwithstring:get_url];//get_url is a macro-defined URL that creates a header File in which the macro defines the URL.

Macro definitions:::::

#define GET_URL @ "http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129 &startrecord=1&len=5&udid=1234567890&terminaltype=iphone&cid=213 "
#define POST_URL @ "Http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define Post_body @ "date=20131129&startrecord=1&len=5&udid=1234567890&terminaltype=iphone& cid=213 "
2. Create a request
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
3. Connect to the server
Method One: Block method implementation,//Parameter 1: Request object//Parameter 2: Thread queue//parameter 3:block
[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse * _nullable response, NSData * _nullable data, Nserror * _nullable connectionerror) {
if (Connectionerror = = nil) {
4. Parsing
Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];
NSLog (@ "dic =%@", dic);
First, we open up the sub-threading parsing data
Then refresh the UI in the main thread
}
}];

Method Two: Use delegate to implement &LT;NSURLCONNECTIONDATADELEGATE&GT, replace the above 3.4. Two steps with, and use the first off proxy method
[Nsurlconnection connectionwithrequest:request delegate:self];
}

#pragma mark-nsurlconnectiondatadelegate-related proxy methods
Server starts responding
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response {
Self.resultdata = [Nsmutabledata new];//initialization data
}
Start receiving data This method will be repeated, and each piece of data is stitched together.
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) Data {
[Self.resultdata Appenddata:data];
}
End server
-(void) connectiondidfinishloading: (nsurlconnection *) connection {
Data parsing (parsing based on the specific content that the URL links to)
Nsdictionary *dic = [Nsjsonserialization JSONObjectWithData:self.resultData options:nsjsonreadingallowfragments Error:nil];
NSLog (@ "dic =%@", dic);
}
#pragma mark-nsurlconnection-Asynchronous POST request
-(Ibaction) Postasynchronousrequest: (UIButton *) Sender {
1. Create a URL
Nsurl *url = [Nsurl Urlwithstring:post_url];
2. Create a request
Nsmutableurlrequest *mutablerequest = [Nsmutableurlrequest Requestwithurl:url];
2.5 Set Body
Create a link string
NSString *datastring = post_body;
Encode a connection string
NSData *postdata = [datastring datausingencoding:nsutf8stringencoding];
Set Request format
[Mutablerequest sethttpmethod:@ "POST"];
Set the request body
[Mutablerequest Sethttpbody:postdata];
3. Linked Servers
[Nsurlconnection sendasynchronousrequest:mutablerequest queue:[nsoperationqueue MainQueue] completionHandler:^ ( Nsurlresponse * _nullable response, NSData * _nullable data, Nserror * _nullable connectionerror) {
if (Connectionerror = = nil) {
Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];
}
}];
}

#pragma mark-nsurlsession-get request block implementation
-(Ibaction) Getrequest: (UIButton *) Sender {
Mode One: Use block
1. Create a URL
Nsurl *url = [Nsurl Urlwithstring:get_url];
2. Create a request Nsurlrequest
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
2. Create Session Object
Nsurlsession *session = [Nsurlsession sharedsession];
3. Create Task Request tasks
Nsurlsessiondatatask *task = [Session datataskwithrequest:request completionhandler:^ (NSData * _Nullable data, Nsurlresponse * _nullable response, Nserror * _nullable error) {
4. Parse the relevant data//here The Block execution steps are relatively lean, not in//2. Execute immediately after creating session object
if (Error = = nil) {
Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];
}
}];
5. Core step: Start Task "Don't forget" ============
Cause: The task of the Nsurlsessiontask instance is in a pending state, and if it does not start, it will not go to the implementation part of the block
[Task resume];
#pragma mark-nsurlsession-get Request Protocol implementation
Nsurl *url = [Nsurl Urlwithstring:get_url];
2. Create session
Parameter 1: setting of the Mode
/*
* Defaultsessionconfiguration Default session Mode
* Ephemeralsessionconfiguration instantaneous session mode
* Backgroundsessionconfigurationwithidentifier Background Session mode
*/
Parameter 2: Proxy
Parameter 3: Main thread queue
Nsurlsession *session = [Nsurlsession sessionwithconfiguration:[nsurlsessionconfiguration Defaultsessionconfiguration] Delegate:self Delegatequeue:[nsoperationqueue mainqueue]];//Compliance Agreement < Nsurlsessiondatadelegate>
3. Create a task
Nsurlsessiondatatask *task = [session Datataskwithurl:url];
4. Start
[Task resume];
Implementation method of #pragma mark-nsurlsessiondatadelegate protocol
Server starts responding
-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) Datatask Didreceiveresponse: ( Nsurlresponse *) Response Completionhandler: (void (^) (nsurlsessionresponsedisposition)) Completionhandler {
Allow server response [data is received only if the server is allowed to respond in this place]
Completionhandler (Nsurlsessionresponseallow);
Initialize data to be tiled for fragments later
Self.resultdata = [Nsmutabledata data];
}
Receive Data stitching
-(void) Urlsession: (Nsurlsession *) session Datatask: (Nsurlsessiondatatask *) datatask didreceivedata: (NSData *) Data {
Repeat, and then stitch the relevant fragments
[Self.resultdata Appenddata:data];
}
Data reception complete, network request ended
-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didcompletewitherror: (Nserror *) Error {
Analytical
if (Error = = nil) {
Nsdictionary *dic = [Nsjsonserialization JSONObjectWithData:self.resultData options:nsjsonreadingallowfragments Error:nil];
NSLog (@ "dic =%@", dic);
}
}

#pragma mark-nsurlsession -POST request
-(Ibaction) Postrequest: (UIButton *) Sender {
1. Create a URL
Nsurl *url = [Nsurl Urlwithstring:post_url];
2. Create a request
Nsmutableurlrequest *mutablerequest = [Nsmutableurlrequest Requestwithurl:url];
2.5 Core Settings Body
NSString *bodystring = post_body;
NSData *postdata = [bodystring datausingencoding:nsutf8stringencoding];
[Mutablerequest sethttpmethod:@ "POST"];
[Mutablerequest Sethttpbody:postdata];
3. Create Session Object
Nsurlsession *session = [Nsurlsession sharedsession];
4. Create a Task object
Nsurlsessiondatatask *task = [Session datataskwithrequest:mutablerequest completionhandler:^ (NSData * _Nullable data, Nsurlresponse * _nullable response, Nserror * _nullable error) {
5. Parsing
if (Error = = nil) {
Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];
NSLog (@ "dic =%@", dic);
}
}];
6. Start a task
[Task resume];
}



Web Requests for iOS

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.