您好我是ios的新手,我正在尝试使用NSURLSession向服务器发送一些参数(它们是USERname,USERtype,USERimage) 但基于我的下面的代码图像不是去服务器和如何发送图像到服务器,请帮助我在哪里做错了吗?
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
UIImage *myImage = [UIImage imageNamed:@"myImage.png"];
NSString *myImage = [UIImagePNGRepresentation(myImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
@"IOS TYPE", @"typemap",
myImage,@"image"
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
答案 0 :(得分:0)
尝试使用
UIImage *myImage = [UIImage imageNamed:@"myImage.png"];
NSString *base64Image = [UIImagePNGRepresentation(myImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
答案 1 :(得分:-2)
您可以使用AFNetworking库上传图片。效率更高。
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];
[manager.requestSerializer setValue:[CommonFunctions hmac:sStr withKey:[[NSUserDefaults standardUserDefaults] objectForKey:KEY_ACCESS_TOKEN]] forHTTPHeaderField:@"Signature"];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:[NSString stringWithFormat:@"%@%@",kBaseURL,theFileName] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (finalImageData)
{
[formData appendPartWithFileData:finalImageData name:@"photo" fileName:@"pic.jpg" mimeType:@"image/jpeg" ];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}