如何将Json和Image发布到ios的服务器上

时间:2014-02-21 02:51:32

标签: php ios nsurlrequest

如何将Json和Image发布到服务器上用于ios? 我知道发布Json Data&图片,但我不知道同时张贴Json和Image? 因为我想订购,我需要将用户信息和用户图像发布到服务器。

2 个答案:

答案 0 :(得分:1)

-(void)postMethod   
{   
 NSString *urlString = [NSString stringWithFormat:@"http:********web-services/register_user.php?firstname=%@&lastname=%@&email=%@&password=%@&location=india&device=IPHONE",details.fname,details.lname,details.emailAddress,details.password];   

 UIImage *image=details.pic;
NSData *imageData =UIImageJPEGRepresentation(image, 0.1);
double my_time = [[NSDate date] timeIntervalSince1970];
NSString *imageName = [NSString stringWithFormat:@"%d",(int)(my_time)];
NSString *string = [NSString stringWithFormat:@"%@%@%@", @"Content-Disposition: form-data; name=\"profile_pic\"; filename=\"", imageName, @".jpg\"\r\n\""];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:string] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString*s11=   [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];    
}

答案 1 :(得分:1)

您可以使用AFNetWorking来完成您的要求。