ios中Web服务的单例类
我是iOS新手,在开发过程中,我随时随地都在调用web服务……我想要一个用于get、post、put方法的类……然后调用[self post]; [参数:…]。。。这意味着我想为所有get服务和post调用单个方法。。请帮帮我……怎么样ios中Web服务的单例类,ios,objective-c,iphone,web-services,xcode6,Ios,Objective C,Iphone,Web Services,Xcode6,我是iOS新手,在开发过程中,我随时随地都在调用web服务……我想要一个用于get、post、put方法的类……然后调用[self post]; [参数:…]。。。这意味着我想为所有get服务和post调用单个方法。。请帮帮我……怎么样 NSURL *url = [NSURL URLWithString:@"https://example.com/"]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSURL *url = [NSURL URLWithString:@"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
[httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Request Successful, response '%@'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
For AFNetworking 2.0 (and also using the new NSDictionary syntax):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
从这里可以创建singleton类- 然后,您需要使用完成处理程序创建自己的方法,并在需要的地方调用 示例:Post方法:
+(void)postWebserviceWithURL:(NSString*)webServiceURL withParam:(NSDictionary*)urlParameters withCompletion:(void(^)(NSDictionary*response))completion {
//Your code goes here
}
下面是相关的答案。您应该创建类似webservices的nsobject类,并像这样创建singleton实例对象
+(WebServices *)sharedInstance{
/* Use this to make it a singleton class */
if (sharedObj==Nil) {
sharedObj=[[WebServices alloc]init];
}
return sharedObj;
/**/
}
使用这个单例实例,您可以根据需要调用这些方法
Eg: [[webservices sharedInstance] post];
使用该方法,您可以使用所需的web服务点击,如post、get和put
使用Nsnotifiers使用API命中的响应
+ (instancetype)sharedInstance
{
static CustomClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//Override your constructor for custom initialization if you want
sharedInstance = [[CustomClass alloc] init];
});
return sharedInstance;
}
然后定义CRUD操作的方法
简单地访问
[[CustomClass sharedInstance] POST:...];
[[CustomClass sharedInstance] GET:...];