iOS Encapsulating network requests

Source: Internet
Author: User

There are often network requests in iOS that can be encapsulated for ease of use:

Network encapsulation Request class:

. h file:



#import <Foundation/Foundation.h>


@interface Nethandler:nsobject


// no return value , according to the characteristics of the network request, different places is the requested address and the way to analyze the data is not the same, that is, the two parts as a method parameter

+ (void) Getdatawithurl: (nsstring *) str complietion: (void(^) (nsdata *data)) Block


. M File:

If the interface is a POST request, you can change the get to post directly

#import "NetHandler.h"


@implementation Nethandler


+ (void) Getdatawithurl: (nsstring *) str complietion: (void (^) (nsdata *)) block

{

nsstring * urlstr = [strstringbyaddingpercentescapesusingencoding: Nsutf8stringencoding];

nsurl *url = [nsurlurlwithstring: urlstr];

nsmutableurlrequest *request = [nsmutableurlrequestrequestwithurl : URL cachepolicy:nsurlrequestuseprotocolcachepolicytimeoutinterval:60 ];

Request. HttpMethod =@ "GET";

//////////// Connection Setup

[nsurlconnectionsendasynchronousrequest: Request queue: [nsoperationqueue Mainqueue] completionhandler: ^ (nsurlresponse *response,nsdata *data, nserror *connectionerror) {

//// processing data

if (Data! = Nil) {

// when the returned data is not empty, call block

Block (data);

}

Block (data);

// Let the view refresh Refresh Data

///[tableview Reloaddata];

//label.text = ...

}];


}





iOS Encapsulating network requests

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.