Ios 在后台线程的文档目录中使用QRCode保存图像

Ios 在后台线程的文档目录中使用QRCode保存图像,ios,objective-c,iphone,background-process,background-thread,Ios,Objective C,Iphone,Background Process,Background Thread,我正在开发一个应用程序,其中我从iOS gallery中挑选了10幅图像,然后生成所有图像的QRCode,然后使用后台线程将所有内容保存在文档目录中,但问题是当我更改选项卡栏时,意味着在处理后开始,当我移动到另一个选项卡栏视图时,后台线程停止,我仅获取存储的3或4个图像。我使用了不同的后台函数来实现这一点,就像我使用了NSOperationQueue一样,我还创建了单独的类,然后尝试保存,但没有成功。我使用的代码: - (void)elcImagePickerController:(ELCIm

我正在开发一个应用程序,其中我从iOS gallery中挑选了10幅图像,然后生成所有图像的QRCode,然后使用后台线程将所有内容保存在文档目录中,但问题是当我更改选项卡栏时,意味着在处理后开始,当我移动到另一个选项卡栏视图时,后台线程停止,我仅获取存储的3或4个图像。我使用了不同的后台函数来实现这一点,就像我使用了NSOperationQueue一样,我还创建了单独的类,然后尝试保存,但没有成功。我使用的代码:

 - (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
    {
       NSLog(@"%@",info);
        [self dismissViewControllerAnimated:YES completion:nil];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

         [self saveallD:info];

            dispatch_async(dispatch_get_main_queue(), ^{

            });
        });
    }

    -(void)saveallD:(NSArray*)info
    {
        // int i=0;
        for (NSDictionary *dict in info)
        {
            if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
            {
                // i++;

                if ([dict objectForKey:UIImagePickerControllerOriginalImage])
                {
                    UIImage* chosenImage=[dict objectForKey:UIImagePickerControllerOriginalImage];

                    NSData *imageData = UIImagePNGRepresentation(chosenImage);

                    CGFloat scale= (100*1024)/(CGFloat)[imageData length]; // For 100KB.

                    UIImage *small_image=[UIImage imageWithCGImage:chosenImage.CGImage scale:scale orientation:chosenImage.imageOrientation];

                    NSData *imagefinaldata = UIImageJPEGRepresentation(small_image, scale*1.00);

                    //UIImage *imgCompressed = [self compressImage:chosenImage];

                    //NSData *imagefinaldata = UIImagePNGRepresentation(imgCompressed);

                    BOOL qrcodedetected = NO;

                    [[NSUserDefaults standardUserDefaults] setObject:imagefinaldata forKey:@"imagesaved"];

                    // QRCode detector
                    NSDictionary *detectorOptions = @{ CIDetectorAccuracy : CIDetectorAccuracyHigh };
                    CIDetector *faceDetector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:detectorOptions];
                    NSArray *features = [faceDetector featuresInImage:chosenImage.CIImage];
                    CIQRCodeFeature *faceFeature;
                    for(faceFeature in features)
                    {
                        qrcodedetected = YES;
                        self.decodedstr = [NSString stringWithFormat:@"%@",faceFeature.messageString];
                        break;
                    }

                    if (!qrcodedetected)
                    {

                        int timestamp = [[NSDate date] timeIntervalSince1970];

                        NSString*selectedFolder=[[NSUserDefaults standardUserDefaults] valueForKey:@"SelectedFolder"];

                        if ([selectedFolder isEqualToString:@""] || [selectedFolder isKindOfClass:[NSNull class]] || selectedFolder.length==0 )
                        {
                            selectedFolder=@"Default";
                        }

                        //dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 2), ^{
                            // time-consuming task

                        NSLog(@"basepath..%@",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]);

                        NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",selectedFolder]];

                        //NSString *QRstringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"QRimages"];


                        if ([[NSFileManager defaultManager] fileExistsAtPath:stringPath])
                        {
                            // [imagefinaldata writeToFile:savedImagePath atomically:NO];
                            //                     stringPath = [stringPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d",timestamp]];

                            NSString *stringPath2 = [stringPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d",timestamp]];
                            NSString *savedImagePath = [stringPath2 stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",timestamp]];

                            [self writeImageToFile:stringPath2 :savedImagePath :imagefinaldata];

                            NSString *savedAudioPath = [stringPath2 stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.m4a",timestamp]];

                            //NSData*recordedAudioData=[NSData dataWithContentsOfURL:_recorder.url];

                            if ([autoRecordingCheck isEqualToString:@"ON"])
                            {
                            [self writeAudioToFile:stringPath2 :savedAudioPath];
                            }


                        }


                        else
                        {
                            [[NSFileManager defaultManager]createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:nil];

                            NSString *stringPath2 = [stringPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d",timestamp]];
                            NSString *savedImagePath = [stringPath2 stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",timestamp]];

                            [self writeImageToFile:stringPath2 :savedImagePath :imagefinaldata];

                            NSString *savedAudioPath = [stringPath2 stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.m4a",timestamp]];

                            //NSData*recordedAudioData=[NSData dataWithContentsOfURL:_recorder.url];

                            if ([autoRecordingCheck isEqualToString:@"ON"])
                            {
                            [self writeAudioToFile:stringPath2 :savedAudioPath];
                            }
                            //  [imagefinaldata writeToFile:savedImagePath atomically:NO];

                        }



                        NSString *savedImagePath = [stringPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",timestamp]];

                        CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
                        [filter setDefaults];

                        NSData *data = [savedImagePath dataUsingEncoding:NSUTF8StringEncoding];
                        [filter setValue:data forKey:@"inputMessage"];

                        CIImage *outputImage = [filter outputImage];

                        CIContext *context = [CIContext contextWithOptions:nil];
                        CGImageRef cgImage = [context createCGImage:outputImage
                                                           fromRect:[outputImage extent]];

                        UIImage *image = [UIImage imageWithCGImage:cgImage
                                                             scale:1.0
                                                       orientation:UIImageOrientationUp];

                        // Resize without interpolating
                        UIImage *resized = [self resizeImage:image
                                                 withQuality:kCGInterpolationNone
                                                        rate:5.0];

                        NSData* QRdata = UIImagePNGRepresentation(resized);

                        NSString *stringPath2 = [stringPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d",timestamp]];
                        NSString *savedImagePath2 = [stringPath2 stringByAppendingPathComponent:[NSString stringWithFormat:@"QR%d.png",timestamp]];

                        [self writeQRToFile:stringPath2 :savedImagePath2 :QRdata];

                        // [self performSegueWithIdentifier:@"addfilters" sender:nil];

    //                        dispatch_async(dispatch_get_main_queue(), ^{
    //                            [SVProgressHUD dismiss];
    //                        });
    //                        
    //                    });
                    }

                    else
                    {
                        [self galleryalert];
                    }

                }
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }

如果有人有任何类型的解决方案,请让我知道。我们将不胜感激。提前谢谢

这是我刚才说的代码。根据您的需要进行更改

背景操作.h

@protocol BackgroundOperationDelegate <NSObject>

-(void)operationCompleted;
-(void)operationInterrupted;


@end


@interface BackgroundOperation : NSObject


@property (nonatomic, weak) id<BackgroundOperationDelegate> delegate;

+(BackgroundOperation*)sharedInstance;

-(void)saveallD:(NSArray*)info;

@end
您可以在viewcontroller中进行如下调用

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
 {
    NSLog(@"%@",info);
    [self dismissViewControllerAnimated:YES completion:nil];

    [[BackgroundOperation sharedInstance] setDelegate:self];
    [[BackgroundOperation sharedInstance] saveallD:info];



 }

确保覆盖视图控制器中的BackgroundOperationDelegate方法,以便在任务完成后获得回调。以下是我所说的代码。根据您的需要进行更改

背景操作.h

@protocol BackgroundOperationDelegate <NSObject>

-(void)operationCompleted;
-(void)operationInterrupted;


@end


@interface BackgroundOperation : NSObject


@property (nonatomic, weak) id<BackgroundOperationDelegate> delegate;

+(BackgroundOperation*)sharedInstance;

-(void)saveallD:(NSArray*)info;

@end
您可以在viewcontroller中进行如下调用

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
 {
    NSLog(@"%@",info);
    [self dismissViewControllerAnimated:YES completion:nil];

    [[BackgroundOperation sharedInstance] setDelegate:self];
    [[BackgroundOperation sharedInstance] saveallD:info];



 }

确保覆盖视图控制器中的BackgroundOperationDelegate方法,以便在任务完成后获得回调

可以尝试singleton@Sanniv:你能再多描述一下吗。谢谢可以试试吗singleton@Sanniv:你能再多描述一下吗。谢谢我尝试过你的建议,但它仍然保存了4或5个图像的10。感谢您的努力。那么这不是更改选项卡栏(即进程中断)的问题,否则该问题将通过此解决方案解决。这一定是图像数据的问题,在4-5个图像之后的某个地方出现故障。尽量不要将图像数据保存到NSUserDefaults中。我已经尝试了你的建议,但它仍然保存了10个图像中的4个或5个。感谢您的努力。那么这不是更改选项卡栏(即进程中断)的问题,否则该问题将通过此解决方案解决。这一定是图像数据的问题,在4-5个图像之后的某个地方出现故障。尽量不要将图像数据保存到NSUserDefaults。。