Sending an HTTP POST request on iOS

前端 未结 7 1080
梦谈多话
梦谈多话 2020-11-22 12:04

I\'m trying to send an HTTP Post with the iOS application that I\'m developing but the push never reaches the server although I do get a code 200 as response (from the urlco

7条回答
  •  梦谈多话
    2020-11-22 12:45

    Objective C

    Post API with parameters and validate with url to navigate if json
    response key with status:"success"

    NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
        NSLog(@"%@",string);
        NSURL *url = [NSURL URLWithString:string];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        NSURLResponse *response;
        NSError *err;
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
        NSLog(@"responseData: %@", responseData);
        NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"responseData: %@", str);
            NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                             options:kNilOptions
                                                               error:nil];
        NSDictionary* latestLoans = [json objectForKey:@"status"];
        NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
        NSString *str3=@"success";
        if ([str3 isEqualToString:str2 ])
        {
            [self performSegueWithIdentifier:@"move" sender:nil];
            NSLog(@"successfully.");
        }
        else
        {
            UIAlertController *alert= [UIAlertController
                                     alertControllerWithTitle:@"Try Again"
                                     message:@"Username or Password is Incorrect."
                                     preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action){
                                                           [self.view endEditing:YES];
                                                       }
                                 ];
            [alert addAction:ok];
            [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
            [self presentViewController:alert animated:YES completion:nil];
            [self.view endEditing:YES];
          }
    

    JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code

    **

提交回复
热议问题