大佬教程收集整理的这篇文章主要介绍了objective-c – 在Xcode中使用NSURLConnection发送JSON数据,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
NSDictionary *data = [NSDictionary DictionaryWithObject:@"test sending ios" forKey:@"value1"]; NSError *error; NSData *jsonData = [NSJSONserialization dataWithJSONObject:data options:kNilOptions error:&error]; NSURL *url = [NSURL URLWithString:@"http://webserveraddress"]; NSMutableURLrequest *req = [NSMutableURLrequest requestWithURL:url cachePolicy:nil timeoutInterval:60]; [req SETVALue:@"application/json" forhttpHeaderField:@"Accept"]; [req SETVALue:@"application/json" forhttpHeaderField:@"Content-Type"]; [req SETVALue:[NSString StringWithFormat:@"%d",[jsonData length]] forhttpHeaderField:@"Content-Length"]; [req sethttpR_767_11845@ethod:@"POST"]; [req sethttpBody:jsonData]; NSString *retStr = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousrequest:req returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
例
NSString * key = [NSString StringWithFormat:@"var1=%@&var2=%@&var3=%@",@"var1String",@"var2String",[NSnumber numberWithBool:YES]]; NSURL * url = [NSURL URLWithString:@"http://webserver.com/yourScriptPHP.PHP"]; NSMutableURLrequest * request = [NSMutableURLrequest requestWithURL:url]; [request sethttpR_767_11845@ethod:@"POST"]; [request sethttpBody:[key dataUsingEncoding:NSUTF8StringEncoding]]; [[NSURLConnection alloc] initWithrequest:request delegate:self]; // this is for you to be able to get your server answer. // you will need to make your class a delegate of NSURLConnectionDelegate and NSURLConnectionDataDelegate myClassPointerData = [[NSMutableData data] retain];
实行
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [myClassPointerData appendData:data] } -(void)connection:(NSURLConnection *)connection DidFinishLoading { // do what you want with myClassPointerData the data that your server did send you BACk here // for info on your server PHP script you just need to do: echo json_encode(array('var1'=> $var1,'var2'=>$var2...)); // to get your server sending an answer }
以上是大佬教程为你收集整理的objective-c – 在Xcode中使用NSURLConnection发送JSON数据全部内容,希望文章能够帮你解决objective-c – 在Xcode中使用NSURLConnection发送JSON数据所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。