简体   繁体   English

将多个图像上传到服务器时,应用程序占用大量内存

[英]App consuming a lot memory when uploading multiple image to sever

In my app there is need to upload multiple image to server. 在我的应用程序中,需要将多个图像上传到服务器。 when we going to upload image to server ONE BY ONE or ALL IMAGE once's. 当我们要一次一次将图像上传到服务器一次或全部图像时。

The basic problem is . 基本问题是。

  1. app consuming a lot memory when uploading image to server. 将图片上传到服务器时,该应用会占用大量内存。
  2. memory that was consuming by app not release after uploading image. 上传图像后,应用程序消耗的内存无法释放。

here is code for uploading image to server. 这是用于将图像上传到服务器的代码。 using simple AFNetwortking. 使用简单的AFNetwortking。

-(void) uploadImageToServerOneByOne:(int)count andImage:(UIImage*)img         {
NSMutableDictionary *parem_dict;

if (parem_dict == nil) {
    parem_dict = [[NSMutableDictionary alloc]init];
}

[parem_dict setObject:@"jpeg" forKey:@"extension"];
[parem_dict setObject:@706 forKey:@"order_id"];
[parem_dict setObject:@"gallary" forKey:@"image_type"];
[parem_dict setObject:@(count+1) forKey:@"count"];
[parem_dict setObject:@(1) forKey:@"product_id"];
[parem_dict setObject:@"SNAPBOOK" forKey:@"type"];

manager.requestSerializer.timeoutInterval = 1200 ;
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
[manager POST:@"http://52.42.247.73:8080/anaventures/image/upload" parameters:parem_dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

    [formData appendPartWithFileData:UIImageJPEGRepresentation(img, 0.5) name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg"];

    [parem_dict removeAllObjects];
    formData = nil;

} progress:^(NSProgress * _Nonnull uploadProgress) {
    NSLog(@"%f",uploadProgress.fractionCompleted);

} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    [MyLoader hideLoadingView];
    if (count + 1 < imageArray.count) {

        [self uploadImageToServerOneByOne:count +1 andImage:imageArray[count+1]];

    }else{

        [MyLoader hideLoadingView];

        NSLog(@" image successfully uploaded  -------- ohhhhhhhhooooooooooo!");

    }
    NSLog(@"success");

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    [MyLoader hideLoadingView];
    NSLog(@"fail%@", error.localizedDescription);
}];
}

Thanks in advance 提前致谢

Your problem is you did not use async methods to upload images. 您的问题是您没有使用异步方法上传图像。

I show you a upload image method and example: 我向您展示了上传图片的方法和示例:

Util method:
+ (void)uploadImage:(UIImage *)image withUrl:(NSString *)uploadUrl withBlock:(void (^)(NSString *))returnUrl {

UIImage *img = image;

//UIImage *com_img = [Util compressImage:img toMaxFileSize:25 * 1000];  // max is 250kb   // 50 *1000 :333759

UIImage *com_img_before = [Util imageCompressForWidth:img targetWidth:80];

UIImage *com_img = [Util compressImage:com_img_before toMaxFileSize:25 * 1000];

//NSData *dataObj = UIImagePNGRepresentation(com_img);

NSData *dataObj;
if (UIImagePNGRepresentation(com_img) == nil) {

    dataObj = UIImageJPEGRepresentation(com_img, 1);

} else {

    dataObj = UIImagePNGRepresentation(com_img);
}



NSDictionary * param1 = @{
                          @"id":@1,
                          @"imgFile":dataObj
                          };
AFHTTPSessionManager * session = [AFHTTPSessionManager manager];
session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/xml",@"text/json",@"text/javascript",@"text/html",@"text/plain",@"multipart/form-data",nil];

//url
NSString *url = [NSString stringWithFormat:@"%@%@", BASE_URL, uploadUrl]; // uploadHeader  uploadImages

[session POST:url parameters:param1 constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

    UIImage *img = image; // response
    NSData *data = UIImagePNGRepresentation(img);

    // schoolListItem@2x
    [formData appendPartWithFileData:data name:@"imgFile" fileName:@"imgFile.png"mimeType:@"image/png"];
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {

    NSLog(@"success+%@", responseObject);
    NSString *return_url = [NSString stringWithFormat:@"%@",responseObject[@"data"]]; //
    // pass data by block
    returnUrl(return_url);



} failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
    NSLog(@"fail");
}];


}


 USAGE:

 [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        __block int comemntCount = 0;

        NSString *url = @"prescription/uploadImages"; // the uplad url

        static dispatch_once_t onceToken;
        static dispatch_semaphore_t semaphore;  // sema 
        static dispatch_queue_t queue;

        dispatch_once(&onceToken, ^{
            semaphore = dispatch_semaphore_create(1);
            //queue = dispatch_queue_create("com.MyApp.task", NULL);
            queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
        });


        for (int i = 0; i < _selectedAssets.count; i ++) {  //_photosChooseArr

            dispatch_async(queue, ^{

                dispatch_semaphore_wait(semaphore,  DISPATCH_TIME_FOREVER);
                [Util uploadImage:_selectedPhotos[i] withUrl:url withBlock:^(NSString *returnUrl) {

                    if (i == 0) {
                        files = returnUrl;
                        comemntCount ++;
                        if (comemntCount == _selectedAssets.count) {
                            [MBProgressHUD hideHUDForView:self.view animated:YES];
                            [self doUploadMessageWithFiles:files];

                        }
                    }else { 

                        files = [files stringByAppendingString:[NSString stringWithFormat:@",%@", returnUrl]];
                        comemntCount ++;

                        if (comemntCount == _selectedAssets.count) {
                            [MBProgressHUD hideHUDForView:self.view animated:YES];
                            [self doUploadMessageWithFiles:files];
                            NSLog(@"i = %d, returnUrl = %@, files = %@", i, returnUrl, files);
                        }
                    }

                    dispatch_semaphore_signal(semaphore);

                }];

            });

        }



        /* 3 min after hide the hud  */
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(180.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 60s after close the hud
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });

This is my method to upload image array, and you can copy to your project to research, and I hope can help you. 这是我上传图像数组的方法,您可以将其复制到项目中进行研究,希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么用 UIGraphicsImageRenderer 绘制图像时大量使用 memory? - Why use a lot of memory when drawing image with UIGraphicsImageRenderer? iOS 应用程序 WKWebView 上传图片时出错 - iOS app WKWebView error when uploading image 将图像上传到firebase时,Swift应用程序崩溃了 - Swift app crashes when uploading image to firebase 不在应用程序中时,APNS会导致严重滞后/崩溃 - APNS when not in app causes sever lag/crash 在没有互联网连接的情况下如何防止应用程序在上传图像时崩溃 - How to prevent app crashing when uploading image when there is no internet connection 当App在带有Xcode 5的iOS 7中处于空闲状态时,如何知道哪个对象或代码段正在不断消耗内存? - How to know what object or piece of code is continually consuming memory when App is really in idle state in iOS 7 with Xcode 5? 应用程序中分配了很多内存,如何解决? - A lot of allocated memory in the app, how to fix? 当我使用imageView.layer.shouldRasterize = YES时,我的应用程序占用大量内存 - My app uses a lot of memory when I use imageView.layer.shouldRasterize = YES 在Swift中使用多个图像选择库时,高内存使用率以及该应用程序崩溃后 - High Memory usages and after that app crash ,when using Multiple image selection library in Swift 上传应用截图时appstoreconnect错误IMAGE_TOOL_FAILURE - appstoreconnect error IMAGE_TOOL_FAILURE when uploading app screenshots
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM