Showing posts with label background. Show all posts
Showing posts with label background. Show all posts

Tuesday, September 25, 2018

performBackgroundTask not saving when app in background Swift

Leave a Comment

I'm using Xcode 9 and Swift 4. I start a download of multiple JSON files when the application is in the foreground. The application then parses these files and saves them to CoreData. This works well when the application is in the foreground. However, if the application is in the background, the files still download correctly, but the data is not parsed and saved to CoreData. It's only when the user returns to the foreground that the parsing and saving of data continues.

I have Background Modes turned on - Background Fetch and Remote notifications.

I have around 10 functions that are similar to the one below in which it processes the JSON files concurrently:

func populateStuff(json: JSONDictionary) -> Void {     let results = json["result"] as! JSONDictionary     let stuffData = results["Stuff"] as! [JSONDictionary]      let persistentContainer = getPersistentContainer()      persistentContainer.performBackgroundTask { (context) in         for stuff in stuffData {             let newStuff = Stuff(context: context)             newStuff.stuffCode = stuff["Code"] as? String             newStuff.stuffDescription = stuff["Description"] as? String              do {                 try context.save()             } catch {                 fatalError("Failure to save context: \(error)")             }         }     } }  func getPersistentContainer() -> NSPersistentContainer {     let persistentContainer = NSPersistentContainer(name: "MyProjectName")     persistentContainer.loadPersistentStores { (_, error) in         if let error = error {             fatalError("Failed to load core data stack: \(error.localizedDescription)")         }     }     persistentContainer.viewContext.automaticallyMergesChangesFromParent = true     persistentContainer.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump     return persistentContainer } 

Can anyone advise me on why this might happen and how to over come this?

TIA

1 Answers

Answers 1

Use the beginBackgroundTaskWithName:expirationHandler: method:

func populateStuff(json: JSONDictionary) -> Void {      // Perform the task on a background queue.     DispatchQueue.global().async {          // Request the task assertion and save the ID.         self.backgroundTaskID = UIApplication.shared.beginBackgroundTask (withName: "Finish Network Tasks") {          // End the task if time expires.         UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)         self.backgroundTaskID = UIBackgroundTaskInvalid     }      // Parse the json files      let results = json["result"] as! JSONDictionary     let stuffData = results["Stuff"] as! [JSONDictionary]      let persistentContainer = getPersistentContainer()      persistentContainer.performBackgroundTask { (context) in         for stuff in stuffData {             let newStuff = Stuff(context: context)             newStuff.stuffCode = stuff["Code"] as? String             newStuff.stuffDescription = stuff["Description"] as? String              do {                 try context.save()             } catch {                 fatalError("Failure to save context: \(error)")             }         }     }      // End the task assertion.     UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)     self.backgroundTaskID = UIBackgroundTaskInvalid } 

Calling this method gives you extra time to perform important tasks. Notice the use of endBackgroundTask: method right after the task is done. It lets the system know that you are done. If you do not end your tasks in a timely manner, the system terminates your app.

Read More

Friday, May 6, 2016

Xamarin UWP custom CommandBar

1 comment

I'd like to create a custom CommandBar for the UWP part of my Xamarin project.

I want to make a logo on a background color. The only way to get this, is making a visualbrush or grid, to contain both the background color and the picture.

I've read it can be done like so;

<Window.Resources>     <VisualBrush x:Key="myBrush">         <VisualBrush.Visual>             <Grid>                 <Rectangle Fill="Red" />                 <Image Source="troll.png" />             </Grid>         </VisualBrush.Visual>     </VisualBrush> </Window.Resources> 

I need to add this commandbar during runtime like so:

var _globalAppBar = new CommandBar(); _globalAppBar.Background = [Link  to above layout] 

Questions:

  1. How or where can I add this in my Xamarin UWP project? Add a XAML file?

  2. How can I link during run time to the layout? Or is there a better way to do this?

0 Answers

Read More

Monday, April 25, 2016

Bug recording videos android

Leave a Comment

I'm trying to reocord many videos of 30 seconds in background but, after 20 or 30 videos my service wich is stoping and launching the process to record go slowly.

I have try with a service in the same process and the problem was the same.

My video handler:

@Override public void onCreate() {     super.onCreate();     isRunning = true;     idAlerta = Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "");     videoCount = 1;     mIntentRecorder = new Intent(VideoHandlerService.this, RecorderService.class);     mIntentSend = new Intent(VideoHandlerService.this, SendVideoService.class);     updateVideoTime();     mIntentRecorder.putExtra(Constants.VIDEO_TIME, videoTime);     mIntentRecorder.putExtra(Constants.ID_ALERTA_SERVICE, idAlerta);     mIntentRecorder.putExtra(Constants.COUNT_ALERTA, videoCount);     startService(mIntentRecorder);     newVideo(); } public void newVideo() {     Common.log("new Video");     new Handler().postDelayed(new Runnable() {         @Override         public void run() {             videoCount++;             startNewVideo();             if (videoCount == 2)                 sendVideo(4000);         }     }, videoTime + 2000);  }   public void startNewVideo() {     final Intent intentRecorder = new Intent(VideoHandlerService.this, RecorderService.class);     intentRecorder.putExtra(Constants.VIDEO_TIME, videoTime);     Common.log("idAlerta " + idAlerta);     intentRecorder.putExtra(Constants.ID_ALERTA_SERVICE, idAlerta);     intentRecorder.putExtra(Constants.COUNT_ALERTA, videoCount);     stopService(intentRecorder);     if (Common.getStorage().getBoolean(Constants.RECORDER_ACTIVE, false)) {         if (Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "") != null && Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "").length() > 0) {              new Handler().postDelayed(new Runnable() {                 @Override                 public void run() {                     Common.log("Start service recorder");                     startService(intentRecorder);                     newVideo();                 }             }, 5000);         }     } else         new Handler().postDelayed(new Runnable() {             @Override             public void run() {                 startNewVideo();             }         }, 5000); } 

And this is the process to record:

@Override public int onStartCommand(Intent intent, int flags, int startId) {     Common.log("onStartCommand");     if (intent != null && ((Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "") != null && Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "").length() > 0))) {         windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);         mLayoutParams = new WindowManager.LayoutParams(                 1, 1,                 WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,                 WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,                 PixelFormat.TRANSLUCENT         );         mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;         //Cojo Información del videohandler         Common.log("Intent distinto de null");         mVideoTime = intent.getIntExtra(Constants.VIDEO_TIME, 15000);         mIdAlerta = intent.getStringExtra(Constants.ID_ALERTA_SERVICE);         mVideoCount = intent.getIntExtra(Constants.COUNT_ALERTA, 1);         Common.log("Video time" + mVideoTime);         Common.getStorage().putBoolean(Constants.RECORDER_ACTIVE, true);         initRecording();     }     return START_NOT_STICKY; }  public void initRecording() {     Common.log("INIT RECORDING IN");     surfaceView = new SurfaceView(this);     windowManager.addView(surfaceView, mLayoutParams);     surfaceView.getHolder().addCallback(this);     Common.log("INIT RECORDING OUT"); }  @Nullable @Override public IBinder onBind(Intent intent) {     return null; }   @Override public void onDestroy() {     Common.log("onDestroy Video");     PreferenceHelper preferenceHelper = PreferenceHelper.newInstance(RecorderService.this, Constants.USER_PREFERENCES);     preferenceHelper.setBoolean(Constants.IS_RECORDING, false);     try {         camera.setPreviewCallback(null);     } catch (Exception e){         Common.log("error setPrevieCallback" + (e.getMessage() != null ? e.getMessage() : "sin mensaje"));     }      try {         muteSounds(false);     } catch (Exception e) {         Common.log(e.getMessage());     }     try {         Common.log("media recorder stop");         mediaRecorder.stop();         Common.log("media recorder reset");         mediaRecorder.reset();         Common.log("media recorder release");         mediaRecorder.release();         Common.log("media camera lock");         camera.lock();         Common.log("media camera release");         camera.release();     } catch (Exception e) {      }      Common.log("onDestroy Video");     Common.getStorage().putBoolean(Constants.RECORDER_ACTIVE, false);     RecorderService.super.onDestroy();     System.exit(0); }   @Override public void surfaceCreated(SurfaceHolder holder) {     mSurfaceHolder = holder;     Common.log("SurfaceCreated");     try {         try {             muteSounds(true);         } catch (Exception e) {             Common.log(e.getMessage());         }         Common.log("CAMERA OPEN 1");         try {             camera = Camera.open(1);         } catch (RuntimeException e) {             Common.log(e.getMessage());         }         Common.log("CAMERA OPEN 2");          ///////////////////////////         mCamCoderProfile = CamcorderProfile.get(1, CamcorderProfile.QUALITY_LOW);         mCamCoderProfile.videoCodec = MediaRecorder.VideoEncoder.MPEG_4_SP;         mCamCoderProfile.audioCodec = MediaRecorder.AudioEncoder.AAC;         ///////////////////////////          startRecorder();      } catch (Exception e) {         if (e.getMessage() != null)             Common.log(e.getMessage());     } }   public void muteSounds(boolean mute) {     Common.log("MUTE SOUNDS IN");     AudioManager mgr = ((AudioManager) getSystemService(Context.AUDIO_SERVICE));     mgr.setStreamMute(AudioManager.STREAM_SYSTEM, true);     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {         if (mute) {             mgr.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_MUTE, 0);             mgr.adjustVolume(AudioManager.ADJUST_MUTE, 0);             mgr.adjustVolume(AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE, 0);         } else {             mgr.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_UNMUTE, 0);             mgr.adjustVolume(AudioManager.ADJUST_UNMUTE, 0);         }     } else {         mgr.setStreamMute(AudioManager.STREAM_SYSTEM, mute);         mgr.setStreamMute(AudioManager.STREAM_MUSIC, mute);         if (mute) {             mOlderVolumen = mgr.getStreamVolume(AudioManager.STREAM_RING);             mgr.setStreamVolume(AudioManager.STREAM_RING, 0, 0);         } else             mgr.setStreamVolume(AudioManager.STREAM_RING, mOlderVolumen, 0);          mgr.adjustVolume(AudioManager.ADJUST_LOWER, 0);     }     Common.log("MUTE SOUNDS OUT"); }   public void startRecorder() {     mediaRecorder = new MediaRecorder();     camera.unlock();     mediaRecorder.setCamera(camera);     mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());     mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);     mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);     mediaRecorder.setProfile(mCamCoderProfile);     videoFile = new File(Environment.getExternalStorageDirectory() + "/" +             "wbunker_" + mIdAlerta + "_" + mVideoCount + ".mp4");     Common.log("Video rercorder name file " + videoRecording);     mediaRecorder.setOutputFile(videoFile.getPath());     mediaRecorder.setOrientationHint(270);     try {         Common.log("mediaRecorder prepare");         mediaRecorder.prepare();         Common.log("mediaRecorder prepare");     } catch (Exception e) {     }     Common.log("mediaRecorder start");     mediaRecorder.start();     Common.log("mediaRecorder start");     Common.log("Estoy grabando macho"); } 

When I try to stop the service the services stops, but the camera isn't released even killing the app. Can someone help me?? thanks in advance.

1 Answers

Answers 1

In the onDestroy() method of your service replace the camera.lock() with camera.unLock() and in the startRecorder() method replace the camera.unLock() with camera.lock()

Read More

Tuesday, April 12, 2016

How to use background queue for Google Drive service in Objective C

Leave a Comment

According to documentation of google-api-objectivec-client library:

Queries made from any thread can be called back on a background thread by providing a background queue, as in this example:

service.delegateQueue = [[NSOperationQueue alloc] init]; 

When a delegate queue is specified, there is no requirement for a run loop to be running on the thread that executes the query.

But, it does not work. Handlers are still executed on a main thread.

Question:

How to tell Google Drive service to execute handlers on the background thread?

Code snippet to reproduce

Podfile:

pod 'GTMOAuth2' pod 'GoogleAPIClient/Drive' 

Somewhere in application:

#import "GTLDrive.h" #import "GTMOAuth2Authentication.h"  ...  - (void) applicationDidFinishLaunching:(NSNotification *) aNotification {     service = [[GTLServiceDrive alloc] init];     service.retryEnabled = YES;     service.authorizer = _authorizer //from GTMOAuth2WindowController     service.delegateQueue = [[NSOperationQueue alloc] init];      GTLDriveFile * tempadFolder = [GTLDriveFile object];     folder.name = @"folder-name";     folder.mimeType = @"application/vnd.google-apps.folder";     GTLQueryDrive * query = [GTLQueryDrive queryForFilesCreateWithObject: folder uploadParameters: nil];      [service executeQuery: query completionHandler:                                         ^(GTLServiceTicket * ticket,                                          GTLDriveFile * updatedFile,                                          NSError * error) {                                              if ([NSThread isMainThread]) {                                                   NSLog(@"This is a main thread!");                                              }                                           } } 

1 Answers

Answers 1

This bug was fixed in this commit and released in GoogleAPIClient 1.0.2.

For now code behaves according to documentation:

Queries made from any thread can be called back on a background thread by providing a background queue, as in this example

service.delegateQueue = [[NSOperationQueue alloc] init]; 
Read More