Background:
The recent project to do upload image function, the image must be high-definition, so do not let the compression, upload pictures are a lot of, such as hundreds of, this if it is used AFN, the picture directly for the loop added to the formdata will appear a problem, temporary variable too much, resulting in memory tension, the final program rushed to collapse. It was previously written using an auto-release pool to solve it, but it was not very effective. If you upload a lot of words, memory is still unbearable.
Solution one applies to a small number of pictures such as 40 pictures
I wrote earlier in this, you can see the method of automatic release of the pool, if you upload a few pictures, you can use this method. It's simple, too. Link Here http://www.jianshu.com/p/9e84fe63d5c0
Workaround two applies to pictures of a large number of such as 1000 pictures
Think, for very little memory will take up so much? It is because the picture is read into memory in one breath. If we upload 35 images, there will be no problem. How to spread the 1000 pictures separately? So we have to use the knowledge of multithreading. Create a queue. And then pass it all. Be careful not to save the file in the queue, as long as you first save a filename, execute the time to read the contents of the file. If you pass the image to the queue, the memory will still explode. So save a picture name. A string must not have an image occupied by a large memory bar. On the code bar. My picture comes from the album, so I use the image ID.
/** Create a queue and start uploading pictures @param localidarray get an array of picture IDs for the album, if you are local, pass the image name array, or the sandbox file name array */-(void) Uploadoperation: (Nsarray *) localidarray{nsoperationqueue *queue = [[Nsoperationqueue alloc]init]; Self.queue = queue; This is the control to upload a few pictures at the same time, if it is 1 is the serial queue. I am 4, is a parallel queue. Queue.maxconcurrentoperationcount = 4; for (int i = 0; i<localidarray.count; i++) {//Plus auto-release pool, timely release temporary variables to prevent memory crashes @autoreleasepool { NSString *imagename = [NSString stringwithformat:@ "up_%d.jpg", I]; WS (weakself)//Create a task nsblockoperation *uploadoperation = [nsblockoperation blockoperationwithblock: ^{[weakself uploadtaskwithlocalid:localidarray[i] Imageount:LocalIdArray.count imagename:i Magename]; }]; Add a task to the queue [addoperation:uploadoperation]; }}}/** start uploading a single picture @param the ID of the localid image @param count total uploads how many pictures @param imageName the name of the picture */-(void) Uploadtaskwithlocalid: (NSString *) localid Imageount: (Nsinteger) Count ImageName: (NSString *) imagename{//conversion via Image ID For image, it's simpler if it's a picture name or a sandbox picture file name. Customalbumtool *customalbumtool = [Customalbumtool Sharedcustomalbumtool]; Phfetchresult<phasset *> *upassetarr = [Phasset fetchassetswithlocalidentifiers:@[localid] options:nil]; Phasset *asset = [Upassetarr firstobject]; UIImage *image = [Customalbumtool getimagewithasset:asset targetsize:phimagemanagermaximumsize]; AFN uploaded parameters Nsmutabledictionary *dic = [Nsmutabledictionary dictionary]; dic[@ "xxx"] = [userdatacenter xxx]; dic[@ "xxx"] = self.xxx; Because AFN uploads are executed asynchronously, a semaphore is created. is to perform the next task only after a task has been completely completed. The addition of the semaphore is to convert the AFN to synchronous. If not converted. Queue.maxconcurrentoperationcount = 1, there is no way to synchronize in the queue. dispatch_semaphore_t semaphore = dispatch_semaphore_create (0); WS (weakself) [swaynetworking uploadwithurl:uploadmodelurl parameters:dic constructingbodywithblock:^ (id< Afmultipartformdata> formData) { NSData *data = uiimagejpegrepresentation (image, 1.0); [FormData appendpartwithfiledata:data name:@ "file" Filename:imagename mimetype:@ "Image/jpeg"]; } withprogress:^ (Nsprogress *uploadprogress) {} success:^ (id responseobject) {//Picture succeeded let Semaphore plus 1 Dispatch_semaphore_signal (semaphore); } failure:^ (Nserror *error) {//Picture failed to increase the semaphore by 1 dispatch_semaphore_signal (semaphore); }]; Semaphore waits. Dispatch_time_forever always wait for it. Dispatch_semaphore_wait (semaphore, dispatch_time_forever); }
Monitoring all successfully refreshed UI, you can define an int variable, upload a successful picture plus 1. If equal to the total number of pictures is the equivalent of uploading completed, then refresh the UI bar. You can also create a task that uploads successfully to refresh the UI. Add Dependencies. Perform a refresh UI in the task.
/** Create a queue and start uploading pictures @param localidarray get an array of picture IDs for the album, if you are local, pass the image name array, or the sandbox file name array */-(void) Uploadoperation: (Nsarray *) localidarray{nsoperationqueue *queue = [[Nsoperationqueue alloc]init]; Self.queue = queue; This is the control to upload a few pictures at the same time, if it is 1 is the serial queue. I am 4, is a parallel queue. Queue.maxconcurrentoperationcount = 4; Nsblockoperation *completionoperation = [Nsblockoperation blockoperationwithblock:^{[[NSOperationQueue MainQueue] addoperationwithblock:^{//Back to main thread execution, easy to update UI, etc.}]; }]; for (int i = 0; i<localidarray.count; i++) {//Plus auto-release pool, timely release temporary variables to prevent memory crashes @autoreleasepool { NSString *imagename = [NSString stringwithformat:@ "up_%d.jpg", I]; WS (weakself)//Create a task nsblockoperation *uploadoperation = [nsblockoperation blockoperationwithblock: ^{[weakself uploadtaskwithlocalid:localidarray[i] Imageount:LocalIdArray.count imagename:imagename]; }]; Add Dependencies. [CompletionopeRation adddependency:uploadoperation]; Add a task to the queue [addoperation:uploadoperation]; }}//The task of refreshing the UI is queued and completionoperation will be called when all upload tasks are completed. [Queue addoperation:completionoperation];}
If your business is not to allow a picture to fail to pass, then when one of the pictures is not successful, then cancel all the tasks directly.
[weakSelf.queue cancelAllOperations];
Wang Banbo
Links: http://www.jianshu.com/p/5162df747879
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
ios-afnetworking3.0 Upload a large number (1000 photos) to the server