NSUrlSession不起作用

时间:2016-02-04 05:12:02

标签: ios objective-c nsurlsession

嗨,我对ios非常新,在我的项目中我使用NSUrlSession来调用服务

但在我的下面的代码中,我维护if和else处理服务器响应的条件,但那些if和else条件没有调用

请帮助我在哪里做个错误的好事?

- (void)viewDidLoad {
    [super viewDidLoad];

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:myurl here]];

                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                       timeoutInterval:60.0];


    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"GET"];
    [request setHTTPBody:[self httpBodyForParamsDictionary:params]];


    //You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {


        if (error) {

            NSLog(@"dataTaskWithRequest error: %@", error);

            NSString * BasicnetworkError = [error localizedDescription];
            NSString * AppendString = @"Http Response failed with the following ";
            NSString * networkError = [AppendString stringByAppendingString:BasicnetworkError];

            [self BasicError1:networkError];
        }

       else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {

            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

            if (statusCode != 200) {

               NSLog(@"Expected responseCode == 200; received %ld", (long)statusCode);

                NSString *statusCodeError = [NSString stringWithFormat: @"Http Response failed with the following code %ld", (long)statusCode];

                [self BasicError1:statusCodeError];
            }
        }

        // If response was JSON (hopefully you designed web service that returns JSON!),
        // you might parse it like so:

        else{

        NSError *parseError;
        id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

        NSLog(@"else condtion");

        if (!responseObject) {

            NSLog(@"JSON parse error: %@", parseError);

        } else {

            NSLog(@"responseObject = %@", responseObject);

            [self MainService:responseObject];
        }

       //if response was text/html, you might convert it to a string like so:
       // ---------------------------------

        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         NSLog(@"final responseString = %@", responseString);
       }
    }];

    [task resume];
}

- (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary{

    NSMutableArray *parameterArray = [NSMutableArray array];

    [paramDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
        NSString *param = [NSString stringWithFormat:@"%@=%@", key, [self percentEscapeString:obj]];
        [parameterArray addObject:param];
    }];

    NSString *string = [parameterArray componentsJoinedByString:@"&"];

    return [string dataUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)percentEscapeString:(NSString *)string{

    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)string,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

1 个答案:

答案 0 :(得分:1)

您的代码中提到了if else阻止错误的情况。请使用以下代码。

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *mainDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                    @"COLLECTION",@"SearchBy",
                                    @"1284",@"SearchKey",
                                    @"",@"Color",
                                    @"",@"PriceFrom",
                                    @"",@"PriceTo",
                                    @"",@"QtyFrom",
                                    @"",@"QtyTo",
                                    nil];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://203.77.214.78/StockManager/SL/SearchProducts"]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[self httpBodyForParamsDictionary:mainDictionary]];


    //You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {


        if (error) {

            NSLog(@"dataTaskWithRequest error: %@", error);

        }
        else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {

            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

            if (statusCode != 200) {

                NSLog(@"Expected responseCode == 200; received %ld", (long)statusCode);

            }else{

                NSError *parseError;
                id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

                NSLog(@"else condtion");

                if (!responseObject) {

                    NSLog(@"JSON parse error: %@", parseError);

                } else {

                    NSLog(@"responseObject = %@", responseObject);

                }

                //if response was text/html, you might convert it to a string like so:
                // ---------------------------------

                NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"final responseString = %@", responseString);
            }
        }
    }];

    [task resume];
}