ios - save image with QRCode in document directory in background thread -


i developing app in have picked 10 images ios gallery , generate qrcode of images , save in document directory using background thread problem when change tab bar means after processing start when move tab bar view background thread stop , 3 or 4 stored images. have used different different background function achive have used nsoperationqueue made separate class tried save not succeeded. code have used:

 - (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;         (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]; // 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);             }         } 

if have type of solution please let me know. appreciated. in advance!

here code talking about. make changes per need.

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];     (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]; // 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);          }      }     if(i+1==info.count)     {         [self.delegate operationcompleted];     }     else     {         [self.delegate operationinterrupted];     } }  @end 

you can make call below in viewcontroller

- (void)elcimagepickercontroller:(elcimagepickercontroller *)picker didfinishpickingmediawithinfo:(nsarray *)info  {     nslog(@"%@",info);     [self dismissviewcontrolleranimated:yes completion:nil];      [[backgroundoperation sharedinstance] setdelegate:self];     [[backgroundoperation sharedinstance] savealld:info];     } 

make sure override backgroundoperationdelegate methods in view controller callbacks once task completed


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -