2016-02-04 1 views
0

Salut je suis très nouveau pour ios et dans mon projet, je me sers NSUrlSession pour appeler les servicesNSUrlSession ne fonctionne pas

mais dans mon code ci-dessous je dois maintenir si et conditions d'autre pour la réponse du serveur de remise, mais les cas et conditions d'autre ne pas appeler

s'il vous plaît aidez-moi où était le mistack happand?

- (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)@":/[email protected]!$&'()*+,;=", 
                       kCFStringEncodingUTF8)); 
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"]; 
} 
+0

Hi. Qu'est-ce que vous obtenez en sortie sur la console? – KiranJasvanee

+0

rien au-dessus si et d'autres contions n'appellent pas c'est mon problème – AbhiRam

+0

là sinon bloc ne pas appeler s'il n'y a pas de problèmes de réseau – AbhiRam

Répondre

1

Il y avait un cas de mauvais sinon sinon le bloc mentionné dans votre code. Veuillez utiliser le code ci-dessous.

- (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]; 
} 
+0

ok wiat je vais vérifier cela dans mon projet – AbhiRam

+0

setHTTPBody n'est pas nécessaire de définir dans votre cas. S'il s'agit d'une requête GET, HTTPBody ne sera pas disponible, mais dans le cas d'une requête POST, vous aurez besoin de HTTPBody pour le définir. – KiranJasvanee

+0

Je vais poster mon projet d'échantillon en utilisant la méthode de post s'il vous plaît pouvez-vous modifié mon erreur? – AbhiRam