进行HTTP请求API调用

时间:2013-10-06 18:32:37

标签: ios objective-c

我在构建的IOS SDK中有以下代码:

+ (void) makeRequestToEndPoint:(NSString *) endpoint values:(NSMutableDictionary *) params onCompletion:(SDKCompletionBlock) responseHandler
{
    [params setObject: key forKey: @"key"];

    NSString * urlString = [self createApiUrlFromEndpoint: endpoint];
    NSURL * url = [NSURL URLWithString: urlString];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"charset" forHTTPHeaderField:@"utf-8"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = [[params urlEncodedString] dataUsingEncoding:NSUTF8StringEncoding];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {

        NSError * dicError = nil;
        NSDictionary * dictionary = nil;

        if([data length] >= 1) {
            dictionary = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error: &dicError];
        }

        responseHandler(dictionary, error);
    }];

}

因此,使用SDK的人可以通过执行以下操作来进行API调用:

[SDK makeRequestToEndpoint:@]

上述代码的最佳构建方式​​(处理错误处理,响应处理等的最佳方法)是什么,以方便人们使用SDK?

1 个答案:

答案 0 :(得分:0)

有许多开源框架,您可以从中学习异步网络的良好设计实践。我建议你看看