ios中用于Web服务的单例类

时间:2015-04-14 09:16:28

标签: ios objective-c iphone web-services xcode6

我是iOS新手,而我正在开发我每个地方都在调用Web服务......我想要一个单独的类来获取,发布,放置方法......然后调用[self post];     [参数:....] ...这意味着我想为所有获取服务调用单个方法并发布..请帮助我...它是怎么回事..

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);
}];

3 个答案:

答案 0 :(得分:1)

从这里你可以创建单身类 - How to create singleton class in objective C

然后你需要使用完成处理程序创建自己的方法并调用你想要的地方。

示例:发布方法:

+(void)postWebserviceWithURL:(NSString*)webServiceURL withParam:(NSDictionary*)urlParameters withCompletion:(void(^)(NSDictionary*response))completion {
//Your code goes here
}

答案 1 :(得分:0)

这里是相关的答案。你应该创建类似webservices的nsobject类,并像这样创建单例实例对象。

+(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命中的响应。

答案 2 :(得分:0)

+ (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:...];