解析json 四步走
//1.创建url NSURL *url=[NSURL URLWithString:@"http://127.0.0.1:8080/MJServer/video"]; //2.创建请求 NSURLRequest *request=[NSURLRequest requestWithURL:url]; //3.发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSD ata *data, NSError *connectionError) { if(connectionError || data==nil){ //MBProgressHUD 为第三方框架
[MBProgressHUD showError:@"网络超时,请稍后"]; return ; } //4.解析json数据 NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
解析登陆界面的api
@interface ViewController () @property (weak, nonatomic) IBOutlet UITextField *user; @property (weak, nonatomic) IBOutlet UITextField *pwd; - (IBAction)loginBtn:(id)sender; @end @implementation ViewController //退出键盘 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; } - (void)viewDidLoad { [super viewDidLoad]; } - (IBAction)loginBtn:(id)sender { NSString *usertext=self.user.text; if(usertext.length==0){ [MBProgressHUD showError:@"输入账号"]; return; } NSString *pwdtext=self.pwd.text; if(pwdtext.length==0){ [MBProgressHUD showError:@"请输入密码"]; return; } // NSLog(@"%@",pwdtext); // // //发送用户名和密码给服务器 NSString *sting=[NSString stringWithFormat:@"http://127.0.0.1:8080/MJServer/login?username=%@&pwd=%@",usertext,pwdtext]; NSURL *url=[NSURL URLWithString:sting]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; //发送一个同步请求 // NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // NSLog(@"%@",data); //返回到主线程 NSOperationQueue *queue=[NSOperationQueue mainQueue]; //发送一个同步请求 [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"%@", [NSThread currentThread]); if(connectionError ||data ==nil){ [MBProgressHUD showError:@"请求失败"]; return; } // 解析返回的json数据 //SONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil json数据转换为oc对象 NSDictionary *tionary=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSString *error=tionary[@"error"]; if(error){ [MBProgressHUD showError:error]; }else{ NSString *secces=tionary[@"secces"]; [MBProgressHUD showSuccess:secces]; } }]; }
时间: 2024-10-04 12:03:40