Objective c 如何使用NSURLSESSION和NSJSONSerialization在ios objective c中发布数据?
我想要json格式的数据, 示例:- [{ 姓名:一,; }, { 姓名:二,;Objective c 如何使用NSURLSESSION和NSJSONSerialization在ios objective c中发布数据?,objective-c,Objective C,我想要json格式的数据, 示例:- [{ 姓名:一,; }, { 姓名:二,; }]; 您需要在NSmutableURL请求中发布数据。我会提供源代码给你,希望它能为你工作 NSString *strurl=[[NSString alloc]initWithFormat:@"%@insert_comment.php",BASE_URL]; NSString *post = [NSString stringWithFormat:@"tip_id=%@&user_id=%@&co
}]; 您需要在NSmutableURL请求中发布数据。我会提供源代码给你,希望它能为你工作
NSString *strurl=[[NSString alloc]initWithFormat:@"%@insert_comment.php",BASE_URL];
NSString *post = [NSString stringWithFormat:@"tip_id=%@&user_id=%@&comment=%@",[self.SeletedTipData objectForKey:@"id"],[userinfo objectForKey:@"id"],CommentTextFiled.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strurl]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
if (postData == nil){
UIAlertView *invalidLogin = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Something Wrong" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[invalidLogin show];
}
else{
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
/*specify the request type */
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
/* set the data to be posted on server into body for "POST"*/
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"dataResponds=%@",dataResponse);
dispatch_async(dispatch_get_main_queue(), ^{
if ([[dataResponse objectForKey:@"status"] isEqualToString:@"true"]) {
NSLog(@"dataResponds=%@",dataResponse);
}else if ([[dataResponse objectForKey:@"status"] isEqualToString:@"false"]){
[CommanFunction displayAlertView:@"Something Wrong"];
}
});
}] resume];
}
我相信此源代码将对您有所帮助。是的,它对我很有用,非常感谢@苏米特