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