0

iOSギャラリーから10枚の画像を選んですべての画像のQRコードを生成し、バックグラウンドスレッドを使用して文書ディレクトリにすべて保存するアプリを開発していますが、私がタブバーを変更すると、処理を開始した後、別のタブバービューに移動してバックグラウンドスレッドを停止し、3つまたは4つの保存された画像しか取得できないということになります。私はNSOperationQueueを使用して別のクラスを作って保存しようとしましたが成功しなかったように、これを実現するために別の異なるバックグラウンド関数を使用しました。コード私は使用しました:画像をQRコードでバックグラウンドスレッドの文書ディレクトリに保存

- (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) 
         { 
          [email protected]"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); 
      } 
     } 

誰かが解決策を持っている場合は、私に知らせてください。それは高く評価されるだろう。前もって感謝します!

+0

完了するとコールバックを得るためにあなたのビューコントローラでBackgroundOperationDelegate方法verrideシングルトン – Sanniv

+0

@Sannivを試すことができます。ありがとう! – Vishal

答えて

0

ここで私が話していたコードです。必要に応じて変更を加えます。

BackgroundOperation.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 

BackgroundOperation.m

#import "BackgroundOperation.h" 

@implementation BackgroundOperation 

static BackgroundOperation *_sharedInstance = nil; 

+(BackgroundOperation*)sharedInstance{ 

    if(_sharedInstance == nil){ 
     _sharedInstance = [[BackgroundOperation alloc] init]; 
    } 
    return _sharedInstance; 
} 


- (id)init { 

    if(self = [super init]) { 

    } 

    return self; 
} 



-(void)saveallD:(NSArray*)infoArray 
{ 

    int i=0; 
    NSArray *info = [NSArray arrayWithArray:infoArray]; 
    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) 
        { 
         [email protected]"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); 

     } 

    } 
    if(i+1==info.count) 
    { 
     [self.delegate operationCompleted]; 
    } 
    else 
    { 
     [self.delegate operationInterrupted]; 
    } 
} 

@end 

あなたがOを確認してください

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

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



} 

あなたのViewControllerに以下のように呼び出すことができますあなたはもう少し説明してもらえ:そのタスクが

+0

私はあなたの提案を試みましたが、それでも10のうち4つまたは5つの画像を保存します。あなたの努力に感謝します。 – Vishal

+0

それでは、タブバーを変更するという問題(プロセスの中断)でなければ、この解決策によって問題が解決されてしまいます。これは、4〜5枚の画像の後のどこかで失敗している画像データの問題でなければなりません。イメージデータをNSUserDefaultsに保存しないでください。 – Sanniv

関連する問題