2015-10-29 3 views
0

Я использую этот кусок кода для данных попадания в URL-адресе.как обрабатывать ответ в json

NSError *error; 
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
NSURL *url = [NSURL URLWithString:@"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"]; 
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url 
                cachePolicy:NSURLRequestUseProtocolCachePolicy 
                timeoutInterval:60.0]; 

[request1 addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request1 addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

[request1 setHTTPMethod:@"POST"]; 
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"company_name", _CompanyName.text, 
         @"email_id", _Email.text,@"password", _Password.text,nil]; 
NSLog(@"Result: %@",request1); 

NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error]; 
[request1 setHTTPBody:postData]; 

NSURLResponse *response = nil; 
// NSError *error = nil; 

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    //Handle your response here 
    NSLog(@"Result: %@",mapData); 
    NSLog(@"Result: %@",request1); 
    NSLog(@"Result: %@",data); 
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; 
    NSLog(@"Result: %@",dictionary); 
    NSLog(@"Result error : %@",error.description); 
}]; 
[postDataTask resume]; 

Значение uitextfield не хранится в URL-адресе, когда я нажал на кнопку, что мне делать здесь?

NSError *error; 

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
NSURL *url = [NSURL URLWithString:@"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"]; 
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url 
                 cachePolicy:NSURLRequestUseProtocolCachePolicy 
                timeoutInterval:60.0]; 

[request1 addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request1 addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

[request1 setHTTPMethod:@"POST"]; 
//NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,@"company_name", 
    //_Email.text,@"email_id", _Password.text,@"password",nil]; 

NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"yyyyy",@"company_name", 
         @"[email protected]",@"email_id", @"XXXXX",@"password",nil]; 

NSLog(@"Result: %@",request1); 

NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error]; 
[request1 setHTTPBody:postData]; 

NSURLResponse *response = nil; 

// NSError * error = nil;

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    //Handle your response here 
    NSLog(@"Result: %@",mapData); 
    NSLog(@"Result: %@",request1); 
    NSLog(@"Result: %@",data); 
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; 
    NSLog(@"Result: %@",dictionary); 
    NSLog(@"Result error : %@",error.description); 


    NSLog(@"answewrv : %@",dictionary); 
    NSLog(@"Result error : %@",error.description); 

}]; 
[postDataTask resume]; 

это обновленный код после внесения поправок. Я получаю ту же ошибку.

+0

, с чем столкнулся вопрос, каким результатом получится NSLog (@ "Результат:% @", request1); и что получилось здесь NSLog (@ "Результат:% @", словарь); –

+0

NSLog (@ "Результат:% @", request1); ; - " {URL: http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration}" –

+0

NSLog (@ "Результат:% @", словарь); ; - Результат: { data = ""; результат = 0; } –

ответ

0

Вы ошибаетесь здесь:

NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"company_name", _CompanyName.text, 
         @"email_id", _Email.text,@"password", _Password.text,nil]; 

Это должно быть

NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,@"company_name", 
         _Email.text,@"email_id", _Password.text,@"password",nil]; 

initWithObjectsAndKeys среднее: object,key, object, key

+0

спасибо за ваш ценный ответ сэр, но теперь я получаю значение мандата, следующим шагом является его добавление в URL-адрес. –

+0

Я думаю, что вы делаете правильно с добавлением словаря к вашему запросу в 'setHTTPBody' – anhtu

+0

@SandeepChaudhary Пожалуйста, попробуйте мой ответ,' NSDictionary * mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text, @ "company_name", _Email.text , @ "email_id", _Password.text, @ "password", nil]; '. Вы все делаете правильно. Просто неверный параметр на строке, на которой я указываю. – anhtu

0

Я сделал также этот тип работы вы можете увидеть это, может быть это поможет вам.

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
    NSURL *url = [NSURL URLWithString:@" your URL "]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                  cachePolicy:NSURLRequestUseProtocolCachePolicy 
                 timeoutInterval:60.0]; 

    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 


    [request addValue:@"*/*" forHTTPHeaderField:@"Accept"]; 

    [request setHTTPMethod:@"POST"]; 

    NSString *mapData = [NSString stringWithFormat:@"username=%@&password=%@&api_key=Your key", usernameField.text,passwordField.text]; 

     NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

    [request setHTTPBody:postData]; 

    NSLog(@"%@", mapData); 



    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

     if(error == nil) 
     { 

      NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; 
      NSLog(@"Data = %@",text); 

      NSError *error = nil; 
      NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

      if(error!=nil) 
      { 
       NSLog(@"error = %@",error); 

      } 

      dispatch_async(dispatch_get_main_queue(), ^{ 
       [self checkUserSuccessfulLogin:json]; 
      }); 
     } 
     else{ 

      NSLog(@"Error : %@",error.description); 

     } 


    }]; 


    [postDataTask resume]; 

} 
- (void)checkUserSuccessfulLogin:(id)json 
{ 
    // NSError *error; 
    NSDictionary *dictionary = (NSDictionary *)json; 


    if ([[dictionary allKeys] containsObject:@"login"]) 
    { 
     if ([[dictionary objectForKey:@"login"] boolValue]) 
     { 
      [self saveLoginFileToDocDir:dictionary]; 
      ItemManagement *i = [[ItemManagement alloc]init]; 
      [self presentViewController:i animated:YES completion:Nil]; 

     } 
     else 
     { 
      NSLog(@"Unsuccessful, Try again."); 
      UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Wrong Username Or Password" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil]; 
      [alertLogin show]; 
     } 
    } 
} 




- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary 
{ 
    NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
    NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0]; 
    NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:@"Login.plist"]; 

    BOOL flag = [dictionary writeToFile:path atomically:true]; 

    if (flag) 
    { 
     NSLog(@"Saved"); 
    } 
    else 
    { 
     NSLog(@"Not Saved"); 
    } 

} 
Смежные вопросы