Guest User

Untitled

a guest
Jun 13th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  Copyright 2013-2017 appPlant GmbH
  3.  
  4.  Licensed to the Apache Software Foundation (ASF) under one
  5.  or more contributor license agreements.  See the NOTICE file
  6.  distributed with this work for additional information
  7.  regarding copyright ownership.  The ASF licenses this file
  8.  to you under the Apache License, Version 2.0 (the
  9.  "License"); you may not use this file except in compliance
  10.  with the License.  You may obtain a copy of the License at
  11.  
  12.  http://www.apache.org/licenses/LICENSE-2.0
  13.  
  14.  Unless required by applicable law or agreed to in writing,
  15.  software distributed under the License is distributed on an
  16.  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17.  KIND, either express or implied.  See the License for the
  18.  specific language governing permissions and limitations
  19.  under the License.
  20.  */
  21.  
  22. #import "APPMethodMagic.h"
  23. #import "APPBackgroundMode.h"
  24. #import <Cordova/CDVAvailability.h>
  25.  
  26. @implementation APPBackgroundMode
  27.  
  28. #pragma mark -
  29. #pragma mark Constants
  30.  
  31. NSString* const kAPPBackgroundJsNamespace = @"cordova.plugins.backgroundMode";
  32. NSString* const kAPPBackgroundEventActivate = @"activate";
  33. NSString* const kAPPBackgroundEventDeactivate = @"deactivate";
  34.  
  35.  
  36. #pragma mark -
  37. #pragma mark Life Cycle
  38.  
  39. /**
  40.  * Called by runtime once the Class has been loaded.
  41.  * Exchange method implementations to hook into their execution.
  42.  */
  43. + (void) load
  44. {
  45.     [self swizzleWKWebViewEngine];
  46. }
  47.  
  48. /**
  49.  * Initialize the plugin.
  50.  */
  51. - (void) pluginInitialize
  52. {
  53.     enabled = NO;
  54.     [self configureAudioPlayer];
  55.     [self configureAudioSession];
  56.     [self observeLifeCycle];
  57. }
  58.  
  59. /**
  60.  * Register the listener for pause and resume events.
  61.  */
  62. - (void) observeLifeCycle
  63. {
  64.     NSNotificationCenter* listener = [NSNotificationCenter
  65.                                       defaultCenter];
  66.    
  67.     [listener addObserver:self
  68.                  selector:@selector(keepAwake)
  69.                      name:UIApplicationDidEnterBackgroundNotification
  70.                    object:nil];
  71.    
  72.     [listener addObserver:self
  73.                  selector:@selector(stopKeepingAwake)
  74.                      name:UIApplicationWillEnterForegroundNotification
  75.                    object:nil];
  76.    
  77.     [listener addObserver:self
  78.                  selector:@selector(handleAudioSessionInterruption:)
  79.                      name:AVAudioSessionInterruptionNotification
  80.                    object:nil];
  81. }
  82.  
  83. #pragma mark -
  84. #pragma mark Interface
  85.  
  86. /**
  87.  * Enable the mode to stay awake
  88.  * when switching to background for the next time.
  89.  */
  90. - (void) enable:(CDVInvokedUrlCommand*)command
  91. {
  92.     if (enabled)
  93.         return;
  94.    
  95.     enabled = YES;
  96.     [self execCallback:command];
  97. }
  98.  
  99. /**
  100.  * Disable the background mode
  101.  * and stop being active in background.
  102.  */
  103. - (void) disable:(CDVInvokedUrlCommand*)command
  104. {
  105.     if (!enabled)
  106.         return;
  107.    
  108.     enabled = NO;
  109.     [self stopKeepingAwake];
  110.     [self execCallback:command];
  111. }
  112.  
  113. #pragma mark -
  114. #pragma mark Core
  115.  
  116. /**
  117.  * Keep the app awake.
  118.  */
  119. - (void) keepAwake
  120. {
  121.     if (!enabled)
  122.         return;
  123.    
  124.     [audioPlayer play];
  125.     [self fireEvent:kAPPBackgroundEventActivate];
  126. }
  127.  
  128. /**
  129.  * Let the app going to sleep.
  130.  */
  131. - (void) stopKeepingAwake
  132. {
  133.     if (TARGET_IPHONE_SIMULATOR) {
  134.         NSLog(@"BackgroundMode: On simulator apps never pause in background!");
  135.     }
  136.    
  137.     if (audioPlayer.isPlaying) {
  138.         [self fireEvent:kAPPBackgroundEventDeactivate];
  139.     }
  140.    
  141.     [audioPlayer pause];
  142. }
  143.  
  144. /**
  145.  * Configure the audio player.
  146.  */
  147. - (void) configureAudioPlayer
  148. {
  149.     NSString* path = [[NSBundle mainBundle]
  150.                       pathForResource:@"appbeep" ofType:@"wav"];
  151.    
  152.     NSURL* url = [NSURL fileURLWithPath:path];
  153.    
  154.    
  155.     audioPlayer = [[AVAudioPlayer alloc]
  156.                    initWithContentsOfURL:url error:NULL];
  157.    
  158.     audioPlayer.volume        = 0;
  159.     audioPlayer.numberOfLoops = -1;
  160. };
  161.  
  162. /**
  163.  * Configure the audio session.
  164.  */
  165. - (void) configureAudioSession
  166. {
  167.     AVAudioSession* session = [AVAudioSession
  168.                                sharedInstance];
  169.    
  170.     // Don't activate the audio session yet
  171.     [session setActive:NO error:NULL];
  172.    
  173.     // Play music even in background and dont stop playing music
  174.     // even another app starts playing sound
  175.     [session setCategory:AVAudioSessionCategoryPlayback
  176.              withOptions:AVAudioSessionCategoryOptionMixWithOthers
  177.                    error:NULL];
  178.    
  179.     // Active the audio session
  180.     [session setActive:YES error:NULL];
  181. };
  182.  
  183. #pragma mark -
  184. #pragma mark Helper
  185.  
  186. /**
  187.  * Simply invokes the callback without any parameter.
  188.  */
  189. - (void) execCallback:(CDVInvokedUrlCommand*)command
  190. {
  191.     CDVPluginResult *result = [CDVPluginResult
  192.                                resultWithStatus:CDVCommandStatus_OK];
  193.    
  194.     [self.commandDelegate sendPluginResult:result
  195.                                 callbackId:command.callbackId];
  196. }
  197.  
  198. /**
  199.  * Restart playing sound when interrupted by phone calls.
  200.  */
  201. - (void) handleAudioSessionInterruption:(NSNotification*)notification
  202. {
  203.     [self fireEvent:kAPPBackgroundEventDeactivate];
  204.     [self keepAwake];
  205. }
  206.  
  207. /**
  208.  * Find out if the app runs inside the webkit powered webview.
  209.  */
  210. + (BOOL) isRunningWebKit
  211. {
  212.     return IsAtLeastiOSVersion(@"8.0") && NSClassFromString(@"CDVWKWebViewEngine");
  213. }
  214.  
  215. /**
  216.  * Method to fire an event with some parameters in the browser.
  217.  */
  218. - (void) fireEvent:(NSString*)event
  219. {
  220.     NSString* active =
  221.     [event isEqualToString:kAPPBackgroundEventActivate] ? @"true" : @"false";
  222.    
  223.     NSString* flag = [NSString stringWithFormat:@"%@._isActive=%@;",
  224.                       kAPPBackgroundJsNamespace, active];
  225.    
  226.     NSString* depFn = [NSString stringWithFormat:@"%@.on%@();",
  227.                        kAPPBackgroundJsNamespace, event];
  228.    
  229.     NSString* fn = [NSString stringWithFormat:@"%@.fireEvent('%@');",
  230.                     kAPPBackgroundJsNamespace, event];
  231.    
  232.     NSString* js = [NSString stringWithFormat:@"%@%@%@", flag, depFn, fn];
  233.    
  234.     [self.commandDelegate evalJs:js];
  235. }
  236.  
  237. #pragma mark -
  238. #pragma mark Swizzling
  239.  
  240. /**
  241.  * Method to swizzle.
  242.  */
  243. + (NSString*) wkProperty
  244. {
  245.     NSString* str = @"YWx3YXlzUnVuc0F0Rm9yZWdyb3VuZFByaW9yaXR5";
  246.     NSData* data  = [[NSData alloc] initWithBase64EncodedString:str options:0];
  247.    
  248.     return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  249. }
  250.  
  251. /**
  252.  * Swizzle some implementations of CDVWKWebViewEngine.
  253.  */
  254. + (void) swizzleWKWebViewEngine
  255. {
  256.     if (![self isRunningWebKit])
  257.         return;
  258.    
  259.     Class wkWebViewEngineCls = NSClassFromString(@"CDVWKWebViewEngine");
  260.     SEL selector = NSSelectorFromString(@"createConfigurationFromSettings:");
  261.    
  262.     SwizzleSelectorWithBlock_Begin(wkWebViewEngineCls, selector)
  263.     ^(CDVPlugin *self, NSDictionary *settings) {
  264.         id obj = ((id (*)(id, SEL, NSDictionary*))_imp)(self, _cmd, settings);
  265.        
  266.         [obj setValue:[NSNumber numberWithBool:YES]
  267.                forKey:[APPBackgroundMode wkProperty]];
  268.        
  269.         [obj setValue:[NSNumber numberWithBool:NO]
  270.                forKey:@"requiresUserActionForMediaPlayback"];
  271.        
  272.         return obj;
  273.     }
  274.     SwizzleSelectorWithBlock_End;
  275. }
  276.  
  277. @end
Add Comment
Please, Sign In to add comment