之前做過的一個社交軟件有上傳圖片的功能個人建議用AFN當然自己寫更好.
話不多說直接上代碼,這里用的是post下面是需要傳入的參數
NSMutableDictionary *dict = [NSMutableDictionary dictionary];? ?
?dict[@"imgType"] = @"1";? ?
?dict[@"accountId"] =userID; ??
?dict[@"content"] = self.textView.text; ?
?dict[@"pubLat"] = @(self.latitude); ??
dict[@"pubLng"] = @(self.longitude);? ??
dict[@"hobbyId"] = @(index);? ?
?NSString *urlStr = KbaseUrl;? ?
?NSMutableArray *imageDatalist = [NSMutableArray array];
然后把圖片的二進制數據添加進來
for (int i = 0;i<self.imageListArr.count;i++){
NSDictionary *dict = self.imageListArr[i];
UIImage *image = [self getImageWith:dict[@"asset"]];
//把圖片轉換為二進制流其中0.4的這個參數是可以自己設定的可以看看傳到后臺的圖片大小,來設置一個合適的值,另外還要有一種思路是可以讓后臺統一做處理
NSData *imageData = UIImageJPEGRepresentation(image, 0.4);
[imageDatalist addObject:imageData];
}
[[DBJNetworkTool sharedNetworkTool] POST:urlStr parameters:dict constructingBodyWithBlock:^(id_Nonnull formData) {
//循環吧二進制數據加入到formdata中
for (int i = 0;i<imageDatalist.count;i++) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
[formData appendPartWithFileData:imageDatalist[i] name:@"myfiles" fileName:fileName mimeType:@"image/png"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"%@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id? _Nullable responseObject) {
dispatch_async(dispatch_get_main_queue(), ^{
[_indicator stopAnimating];
});
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
dispatch_async(dispatch_get_main_queue(), ^{
});
}];