H wrote it inside.
#import <Foundation/Foundation.h>
typedef void (^myblock) (ID object);
@interface Networkhandle:nsobject
+ (void) getdatawithurlstring: (NSString *) string compare: (Myblock) block;
+ (void) postdatawithurlstring: (NSString *) string
Andbodystring: (NSString *) bodystring
Compare: (Myblock) block;
@end
It's written inside M.
#import "NetworkHandle.h"
@interface Networkhandle ()
@property (nonatomic, strong) Nsmutabledata *data;
@end
@implementation Networkhandle
+ (void) getdatawithurlstring: (NSString *) string compare: (Myblock) block{
Do a UTF-8 to the address to prevent the parameter inside the Chinese
NSString *urlstr = [string stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
Convert Address to URL format
Nsurl *url = [Nsurl urlwithstring:urlstr];
Set Request mode
Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
[Request sethttpmethod:@ "GET"];
Synchronous or asynchronous
[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
if (data! = nil) {
Because the type of the data is not determined, the ID generic pointer is used to receive
ID object = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];
Block (object);
}
}];
}
+ (void) postdatawithurlstring: (NSString *) string andbodystring: (NSString *) bodystring compare: (Myblock) block{
NSString *urlstr = [string stringbyreplacingpercentescapesusingencoding:nsutf8stringencoding];
Nsurl *url = [Nsurl urlwithstring:urlstr];
Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
NSString *parstr = bodystring;
NSData *patdata = [Parstr datausingencoding:nsutf8stringencoding];
[Request sethttpmethod:@ "POST"];
[Request Sethttpbody:patdata];
[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
if (data! = nil) {
ID object = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];
Block (object);
}
}];
}
An asynchronous way to encapsulate a get and post