IOS Network Programming code

Source: Internet
Author: User

Viewcontroller.m

16_ Network Programming

Created by lanou3g on 14-12-19.

Copyright (c) 2014 MXT. All rights reserved.

#import "ViewController.h"

#define BASE_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 BASE_POST_URL @ "Http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?"

#define POST @ "date=20131129&startrecord=1&len=5&udid=1234567890&terminaltype=iphone&cid=213 "

@interface Viewcontroller () <NSURLConnectionDataDelegate>

@property (Nonatomic,retain) Nsmutabledata *mutadata;

@end

@implementation Viewcontroller

-(void) Viewdidload {

[Super Viewdidload];

Additional setup after loading the view, typically from a nib.

}

/*

Different points:

1, transfer data to the server mode:

GET: Through URL string.

POST: Via Data

2, the size of the transmitted data:

GET: URL string up to 255 bytes.

POST: Use NSData, capacity over 1G

3. Security:

GET: All data transmitted to the server, displayed in the URL, similar to the password of the Ming input, directly visible.

POST: Data is turned into nsdata (binary data), similar to the secret input of the password, cannot be read directly

*/

GET Synchronization

-(Ibaction) Getsyncbutton: (ID) Sender {

1, create URL

Nsurl *url = [Nsurl Urlwithstring:base_url];

2, create Nsurlrequest Request object

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

2, 1

[Request sethttpmethod:@ "GET"];

3, return result object: Return value information

Nsurlresponse *response = nil;

Nserror *error = nil;

4. Create a linked object nsurlconnection

NSData *data = [nsurlconnection sendsynchronousrequest:request returningresponse:&response error:&error];

NSLog (@ "return type%@", response);//Print return value information

NSLog (@ "--------------------%@", data);

6 parsing

Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil];

NSLog (@ "+++++++++%@", DIC);

NSLog (@ "%@", [dic valueforkey:@ "News"]);

}

Post synchronization

-(Ibaction) Postsyncbutton: (ID) Sender {

1, create URL

Nsurl *url = [Nsurl Urlwithstring:base_post_url];

Set the parameters in the request body to encode

NSString *post = [NSString stringwithformat:post];

NSData *postdata = [post datausingencoding:nsutf8stringencoding];

2, create the Nsurlrequest request object (mutable because you want to set the parameter)

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

2,1

[Request sethttpmethod:@ "POST"];

[Request Sethttpbody:postdata];

nserror *error = nil;

3. Create a linked object Nsurlconnection (sync does not set proxy)

NSData *data = [nsurlconnection sendsynchronousrequest:request returningresponse:nil error:&error];

//NSLog (@ "--------------------%@", data);

6 parsing

Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil];

NSLog (@ "+++++++++%@", DIC);

NSLog (@ "%@", [dic valueforkey:@ "News"]);

}

/*

There are two implementations of asynchronous joins:

1, set proxy, receive data

2, implementing block (multi-threaded)

*/

Get Async

-(Ibaction) Getasyncbutton: (ID) Sender {

Get Async + Block

1, create URL

Nsurl *url = [Nsurl Urlwithstring:base_url];

2, create Nsurlrequest Request object

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

2,1

[Request sethttpmethod:@ "GET"];

Create an action queue

Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];

3, create the linked object Nsurlconnection (parse within block)

__block Viewcontroller *weakself = self;

[Nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse *response, NSData * Data, Nserror *connectionerror) {

3,1 parsing

Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil];

NSLog (@ "+++++++++%@", DIC);

Never update the UI on a child thread

Dispatch_async (Dispatch_get_main_queue (), ^{

Back to the main thread update UI

WeakSelf.textView.text = [NSString stringwithformat:@ "%@", DIC];

});

}];

NSLog (@ ">>>>>>>>>>>>>>><<<>>%lu", _ Textview.retaincount);

[Queue release];

/*

1, create URL

Nsurl *url = [Nsurl Urlwithstring:base_url];

2, create Nsurlrequest Request object

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

2,1

[Request sethttpmethod:@ "GET"];

3. Create a linked object Send request settings Agent

[Nsurlconnection connectionwithrequest:request delegate:self];

*/

}

#pragma mark-nsurlconnectiondatadelegate

Start accepting

-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) respons

{

NSLog (@ "Start accepting");

Self.mutadata = [Nsmutabledata data];

NSLog (@ "%lu", _mutadata.retaincount);

}

Accept Data

-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data

{

NSLog (@ "---------accept data");

[Self.mutadata Appenddata:data];

}

Acceptance complete

-(void) connectiondidfinishloading: (nsurlconnection *) connection

{

NSLog (@ "+ + accepted");

Analytical

Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:_mutadata options:nsjsonreadingmutablecontainers Error: NIL];

NSLog (@ "%@", DIC);

}

-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error

{

NSLog (@ "error");

}

POST Async

-(Ibaction) Postasyncbutton: (ID) Sender {

1, create URL

Nsurl *url = [Nsurl Urlwithstring:base_post_url];

Set the parameters in the request body to encode

NSString *post = [NSString stringwithformat:post];

NSData *postdata = [post datausingencoding:nsutf8stringencoding];

2, create the Nsurlrequest request object (mutable because you want to set the parameter)

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

2,1

[Request sethttpmethod:@ "POST"];

[Request Sethttpbody:postdata];

Create an action queue

Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];

3, create the linked object Nsurlconnection (parse within block)

__block Viewcontroller *weakself = self;

[Nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse *response, NSData * Data, Nserror *connectionerror) {

3,1 parsing

Nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil];

NSLog (@ "+++++++++%@", DIC);

Never update the UI on a child thread

Dispatch_async (Dispatch_get_main_queue (), ^{

Back to the main thread update UI

WeakSelf.textView.text = [NSString stringwithformat:@ "%@", DIC];

});

}];

NSLog (@ ">>>>>>>>>>>>>>><<<>>%lu", _ Textview.retaincount);

[Queue release];

}

-(void) dealloc

{

[_mutadata release];

[_textview release];

[Super Dealloc];

}

-(void) didreceivememorywarning {

[Super didreceivememorywarning];

Dispose of any resources the can be recreated.

}

@end

IOS Network Programming code

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.