iOS上传数据到服务器

前言

iOS7以后,NSURLSession兴起,其强大与方便远胜于NSURLConnection

本文主要介绍使用NSURLSessionUploadTask上传数据或图片

废话少说直接上代码
//上传数据
- (void)uploadData{
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"接口地址"]];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setTimeoutInterval:20];
NSDictionary * dataDic = @{@"key":@"value"};//把要上传的数据存到字典中
NSData * data = [NSJSONSerialization dataWithJSONObject:dataDic
options:NSJSONWritingPrettyPrinted
error:nil];
NSURLSessionUploadTask * uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
//NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}else{
NSLog(@"上传失败");
}
}];
[uploadTask resume];
}
//上传图片
- (void)uploadImage{
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"接口"]];
[request addValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"text/html" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setTimeoutInterval:20];
NSData * imageData = UIImageJPEGRepresentation(要上传的image,1.0);
NSURLSessionUploadTask * uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    }];
    [uploadTask resume];
}

总结

结合上面两个方法可知,上传平常的数据和上传图片不一样的地方就是下面这两行代码了,就是在发送POST请求时,请求头里面记录着要上传的是图片还是一般的数据.
上传一般的数据:
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
上传图片:
[request addValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"]; [request addValue:@"text/html" forHTTPHeaderField:@"Accept"];

你可能感兴趣的:(iOS上传数据到服务器)