我這個掙扎了一會兒多張圖片,如果你正在尋找上傳多張圖片或任何其他類型的文件,可以做到使用AFNetworking 3.0
NSDictionary *params = @{key : value,
..... etc
};
NSString *urlString = @"http://..... your endpoint url";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // only needed if the server is not returning JSON;
NSURLSessionTask *task = [manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (int x = 0 ; x< contentArray.count; x++) {
AttachmentsModel *model = contentArray[x];
if(model.type == ImageAttachmentType){
[formData appendPartWithFileData:model.data name:model.name fileName:model.fileName mimeType:model.mimeType];
}else if(model.type == AudioAttachmentType){
NSURL *urlVideoFile = [NSURL fileURLWithPath:model.path];
[formData appendPartWithFileURL:urlVideoFile name:model.name fileName:model.fileName mimeType:model.mimeType error:nil];
}else{
[formData appendPartWithFileURL:model.url name:model.name fileName:model.fileName mimeType:model.mimeType error:nil];
}
}
} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
[Utility stopLoading];
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"result = %@", result);
id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
if (block) {
//your response comes here
}
} failure:^(NSURLSessionTask *task, NSError *error) {
NSLog(@"error = %@", error);
}];
if (!task) {
NSLog(@"Creation of task failed.");
}
以下內容,這裏是我的AttachmentsModel看起來像:
// AttachmentsModel.h
typedef enum AttachmnetType{
ImageAttachmentType,
AudioAttachmentType,
VideoAttachmentType
} AttachmnetType;
@interface AttachmentsModel : NSObject
@property (strong, nonatomic) NSString *path;
@property (strong, nonatomic) NSData *data;
@property (strong, nonatomic) NSString *mimeType;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *fileName;
@property (strong, nonatomic) NSURL *url;
請注意,您還可以使用NSUUID生成UUID: '的NSString *邊界= [的NSString stringWithFormat:@ 「邊界 - %@」,[NSUUID UUID] UUIDString];' – Olivier
是的,如果你不不需要支持6.0之前的iOS版本,這是一個很好的方法。 – Rob
這是一個夢幻般的答案。榮譽和感謝。 –