Saturday, September 21, 2019

Services For RestKit GET and POST

-(NSURLRequest *)createRequestWithURL:(NSString *)url
                               params:(NSDictionary *)params
                           HTTPMethod:(NSString *)HTTPMethod
{
    NSURL *URL = [[NSURL alloc] initWithString:kBaseURL];
    AFRKHTTPClient *client = [[AFRKHTTPClient alloc] initWithBaseURL:URL];
    
    NSMutableURLRequest *request = [client requestWithMethod:HTTPMethod path:url parameters:params];
    return request;
}

-(void)getObjectFromURL:(NSString *)url
             HTTPMethod:(NSString *)method
                 params:(NSDictionary *)params
             descriptor:(RKResponseDescriptor *)responseDescriptor
             onComplete:(void (^)(id _Nonnull))onCompleteHandler
                onError:(void (^)(NSError * _Nonnull))onErrorHandler
{
    NSURLRequest *request = [self createRequestWithURL:url params:params HTTPMethod:method];
    RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc]
                                           initWithRequest:request
                                           responseDescriptors:@[responseDescriptor]];
    
    [operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation,
                                                RKMappingResult *mappingResult) {
        if(onCompleteHandler)
        {
            onCompleteHandler((mappingResult.set.count > 1) ? mappingResult.set : mappingResult.firstObject);
        }
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        if(onErrorHandler)
        {
            onErrorHandler(error);
        }
    }];
    
    NSOperationQueue *queue = [NSOperationQueue new];
    [queue addOperation:operation];
}

-(void)postObjectFromURL:(NSString *)baseURL
                    path:(NSString *)path
             classObject:(id)classObject
       requestDescriptor:(RKRequestDescriptor *)requestDescriptor
      responseDescriptor:(RKResponseDescriptor *)responseDescriptor
              onComplete:(void (^)(id _Nonnull))onCompleteHandler
                 onError:(void (^)(NSError * _Nonnull))onErrorHandler
{
    if(baseURL == nil || [baseURL isEqualToString:@""])
        baseURL = kBaseURL;
    
    RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:baseURL]];
    [manager addRequestDescriptor:requestDescriptor];
    [manager addResponseDescriptor:responseDescriptor];
    
    [manager postObject:(classObject)
                   path:path parameters:nil
                success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
        if(onCompleteHandler)
            onCompleteHandler((mappingResult.set.count > 1) ? mappingResult.set : mappingResult.firstObject);
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        if(onErrorHandler)
            onErrorHandler(error);
    }];

}

No comments:

Post a Comment