【问题标题】:how I can Modify this code我如何修改此代码
【发布时间】:2015-01-19 02:28:45
【问题描述】:

我正在使用此函数向服务器发送请求并在 NSDictionary 中接收 JSON 响应。

- (void)performRequest:(NSString *)aRequest
{
    NSString *string=[NSString stringWithFormat:@"%@%@",baseURL,aRequest];
    NSURL *url = [NSURL URLWithString: string];
    NSLog(@"string%@",string);
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data, NSError *connectionError)
     {
         if (data.length > 0 && connectionError == nil)
         {
             NSDictionary * greeting = [NSJSONSerialization JSONObjectWithData:data
                                                                      options:0
                                                                        error:NULL];
             NSLog(@"%@",greeting2);
         }
     }];
}

我想要修改它,使其保留一个发送服务 URL 的函数和一个单独的函数,其中 JSON 响应来自 NSDictionary,以便您可以在其他类中重用它们。

【问题讨论】:

    标签: objective-c nsdictionary nsurlconnection nsurl


    【解决方案1】:

    我使用了 iOS 7 引入的网络:NSURLSession。这是我在项目中使用的网络代码。但我建议您改用 AFNetworking。这将为您节省更多时间。这取决于您在应用程序中想要什么。

    + (void)requestOperationWithMethod:(NSString *)method
                           withUrl:(NSString *)url
                            header:(NSDictionary *)header
                            params:(NSDictionary *)params
                        completion:(FHCompletionResultBlock)completion {
    FHNetworking *network = [FHNetworking shareNetworking];
    NSData *bodyData;
    NSError *jsonError = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:&jsonError];
    if (!jsonError) {
        bodyData = data;
    }
    
    // prepare http request header and body data fields
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    for (NSString *key in header.allKeys) {
        [request setValue:header[key] forHTTPHeaderField:key];
    }
    [request setHTTPMethod:method];
    [request setHTTPBody:bodyData];
    [request setTimeoutInterval:30.0f];
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [[network.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        NSError *jsonError = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
    
        if (jsonError)
            completion(nil, jsonError);
        else {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if (httpResponse.statusCode >= 400) {
    
                if (json[@"code"] && json[@"error"]) {
                    NSError *error = [NSError errorWithDomain:@"Error" code:[json[@"code"] integerValue] userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(json[@"error"], nil)}];
                    completion(nil, error);
                }
                else {
                    NSError *error = [NSError errorWithDomain:@"Error" code:-1 userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Unknown error", nil)}];
                    completion(nil, error);
                }
            }
            else {
                completion(json, nil);
            }
        }
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }] resume];
    

    }

    【讨论】:

    • 顺便说一句,我将 NSURLSession 和 NSURLSessionConfiguration 捕获到共享管理器中,以防万一您无法弄清楚。
    • 这里是完成块的定义:typedef void (^FHCompletionResultBlock)(NSDictionary *result, NSError *error);
    【解决方案2】:

    您可以将方法更改为采用 completionHandler 参数本身:

    - (void)performRequest:(NSString *)aRequest completionHandler:(void(^)(NSDictionary *responseObject, NSError *error))completionHandler
    {
        NSString *string=[NSString stringWithFormat:@"%@%@",baseURL,aRequest];
        NSURL *url = [NSURL URLWithString: string];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response,
                                                   NSData *data, NSError *connectionError) {
            if (data.length > 0 && connectionError == nil) { 
                NSError *parseError;
                NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data
                                                                               options:0
                                                                                 error:&parseError];
                completionHandler(responseObject, parseError);
            } else {
                completionHandler(nil, error);
            }
        }];
    }
    

    现在您可以调用它并在完成处理程序中提供您想要的任何内容:

    [self performRequest:requestString completionHandler:^(NSDictionary *responseObject, NSError *error) {
        if (responseObject) {
            // everything is good; use your NSDictionary here
        } else {
            // handle error here
        }
    }];
    

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 2016-07-20
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      相关资源
      最近更新 更多