其实我有json参数
[dictionary setObject:_dateOfBirth.text forKey:@"birth_date"];
[dictionary setObject:_tfCountry.text forKey:@"country"];
[dictionary setObject:_tfEmail.text forKey:@"email"];
[dictionary setObject:@"" forKey:@"fromLogin"];
[dictionary setObject:@1 forKey:@"gender"];
[dictionary setObject:@"signup" forKey:@"methodName"];
[dictionary setObject:_tfContact.text forKey:@"mobile"];
[dictionary setObject:_tfName.text forKey:@"name"];
[dictionary setObject:_tfNickName.text forKey:@"nickname"];
[dictionary setObject:_tfPassword.text forKey:@"password"];
[dictionary setObject:_tfPinCode.text forKey:@"pincode"];
还有一个Image,我必须将profile_pic设置为Key。 现在我已将所有参数转换为数据,并将数据转换为此
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:nil];
// this is your service request url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://proteen2.inexture.com/webservice"]];
// set the content as format
[request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
// this is your response type
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
NSError *err;
NSURLResponse *response;
// send the synchronous connection
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
// here add your server response NSJSONSerialization
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
它适用于Text,现在如何将Image附加到该参数,我只知道Multi Part但没有得到那个Point。请帮忙
答案 0 :(得分:0)
你需要在这里管理很多东西,比如设置boundry
追加图像数据等等。
您应该使用AFNetworking制作非常简单。从github下载并将库拖放到您的项目中并在您的课程中导入AFNetworking.h
然后您可以执行类似的操作,
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]multipartFormRequestWithMethod:@"POST" URLString:@"urlstring" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//Append image here for example;
UIImage *img = tempImageView.image;
NSData *imgData = UIImageJPEGRepresentation(img, 0.5);
[formData appendPartWithFileData:imgData name:@"imagename/serversideparameter" fileName:@"imagename" mimeType:@"image/jpeg"];
} error:nil];
//Send this request to server. Something like,
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"success!!");
NSLog(@"here is the response : %@",responseObject);
}
else{
NSLog(@"Error Occured : %@",error.localizedDescription);
}
}]resume];
您不应该使用NSUrlConnection
,因为它现在已被弃用。最好使用NSUrlSession
我通过AFNetworking
回答过我。
如果您不想使用AFNetworking
,请参阅this stackoverflow post。它在答案中一步一步地有很好的解释。