PhoneGap iOS plugin development and unlimited background operation solution

Source: Internet
Author: User

1. First Develop plugin: because I need to do before the project (according to the situation)

Create a new obj C file in the project's plugins file. Such as

Demo, this will produce two files of Demo.h and DEMO.M.

The. h file is primarily defined by a number of methods, similar to interfaces in Java. (to inherit Cdvplugin)

The. m file is an implementation of the H folder, which enters the appropriate function when the plug-in executes, keeping in mind that when the function is easy to CEO, Uithread is in a blocked state. No, we can start a thread in the function, the function of the start line is as follows:

Java code
    1. Nsthread *thread=[[nsthread alloc]initwithtarget:selft selector:@selector (doinbackground:) object:argumetns];
    2. Doinbackground is the method to be executed in the new thread
    3. [Thread start];
Nsthread *thread=[[nsthread alloc]initwithtarget:selft selector: @selector (doinbackground:) object:argumetns];// Doinbackground is the method to be executed in the new thread [thread start];

I have a few simple code here:

Java code
    1. #Import<foundation/foundation.h>
    2. #Import<cordova/cdvplugin.h>
    3. @Interface Displaynumber:cdvplugin
    4. -(void) Setnumber: (cdvinvokeurlcommand) command;
    5. @end;
#import <Foundation/Foundation.h> #import <Cordova/CDVPlugin.h> @Interface displaynumber:cdvplugin-( void) Setnumber: (cdvinvokeurlcommand) command; @end;

2. Enable plugins in CONFIG.

Add <feature name= "Demo" >

<param name= ' ios-package ' value= ' Demo '/>

</feature>

Here's a note: value is the class name we defined earlier, the name in the face feature refers to the name of the plug-in to be called before we write JS, if you do not understand, write a name written in the same line. (That's what I did)

3 Edit Write Plugin js

Java code
    1. var demo=function () {
    2. }
    3. demo.prototype={
    4. Method:function (fun1,fun2,params) {cordova.exec (fun1//Successful call, FUN2, ' plug-in name ', ' method name of plugin ', [params//parameter array]);
    5. }
    6. }
var demo=function () {   }  demo.prototype={  method:function (fun1,fun2,params) {cordova.exec (called when fun1//succeeds, fun2, ' plugin name ', ' method name of plugin ', [params//parameter array]);}}

If we want to use the demo plugin, we can simply write the new demo (). method (Fun1,fun2,params);//Very simple

Note: We can also in the plugin JS in the new Demo () to a variable, we will not call again when the new one.

About the solution of unlimited operation in the background (there are many solutions on the web)

1. info.plist file added: Required Background modes (is an array form of the built value), after the item0 of the value set to become the APP plays audio or streams audio/video using A Irplay.

2. Locate MainViewController.h under the Classes folder,

Java code
  1. #Import <Cordova/CDVViewController.h>
  2. #Import <Cordova/CDVCommandDelegateImpl.h>
  3. #Import <Cordova/CDVCommandQueue.h>
  4. #Import <AVFoundation/AVFoundation.h>
  5. @interface mainviewcontroller:cdvviewcontroller{
  6. Avaudioplayer *audioplayer;
  7. }
  8. @property (nonatomic) avaudioplayer * audioplayer;
  9. @end
  10. @interface Maincommanddelegate:cdvcommanddelegateimpl
  11. @end
  12. @interface Maincommandqueue:cdvcommandqueue
  13. @end
#import <Cordova/CDVViewController.h> #import <Cordova/CDVCommandDelegateImpl.h> #import <cordova/ cdvcommandqueue.h> #import <AVFoundation/AVFoundation.h> @interface mainviewcontroller:cdvviewcontroller{    Avaudioplayer *audioplayer;} @property (nonatomic) avaudioplayer * audioplayer; @end @interface maincommanddelegate: Cdvcommanddelegateimpl@end@interface Maincommandqueue:cdvcommandqueue@end

Then modify the mainviewcontroller.m file to find the Viewdidload method, modified to:

Java code
  1. -(void) Viewdidload
  2. {
  3. [Super Viewdidload];
  4. additional setup after loading the view from its nib.
  5. dispatch_queue_t dispatchqueue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);
  6. Dispatch_async (Dispatchqueue, ^ (void) {
  7. Nserror *audiosessionerror = nil;
  8. Avaudiosession *audiosession = [Avaudiosession sharedinstance];
  9. if ([Audiosession setcategory:avaudiosessioncategoryplayback Error:&audiosessionerror]) {
  10. NSLog (@"successfully set the audio session.");
  11. } Else {
  12. NSLog (@"Could not set the audio session");
  13. }
  14. NSBundle *mainbundle = [NSBundle mainbundle];
  15. NSLog (@"%@", Mainbundle);
  16. NSString *filepath = [Mainbundle pathforresource:@"Love" oftype:@"wav"];
  17. NSData *filedata = [NSData Datawithcontentsoffile:filepath];
  18. Nserror *error = nil;
  19. NSLog (@"aa%@", FilePath);
  20. Self.audioplayer = [[Avaudioplayer alloc] Initwithdata:filedata error:&error];
  21. if (self.audioplayer! = nil) {
  22. Self.audioPlayer.delegate = self;
  23. [Self.audioplayer setnumberofloops:-1];
  24. if ([Self.audioplayer preparetoplay] && [Self.audioplayer Play]) {
  25. NSLog (@"successfully started playing ...");
  26. } Else {
  27. NSLog (@"Failed to play.");
  28. }
  29. } Else {
  30. NSLog (@"Failed to play.");
  31. }
  32. });
  33. }
-(void) viewdidload{[Super Viewdidload];    Do any additional setup after loading the view from its nib.    dispatch_queue_t dispatchqueue = dispatch_get_global_queue (dispatch_queue_priority_default, 0);        Dispatch_async (dispatchqueue, ^ (void) {nserror *audiosessionerror = nil;        Avaudiosession *audiosession = [Avaudiosession sharedinstance]; if ([Audiosession setcategory:avaudiosessioncategoryplayback Error:&audiosessionerror]) {NSLog (@ "Successful Ly set the audio session. ");        else {NSLog (@ "Could not set the audio session");        } nsbundle *mainbundle = [NSBundle mainbundle];        NSLog (@ "%@", Mainbundle);        NSString *filepath = [Mainbundle pathforresource:@ "Love" oftype:@ "wav"];        NSData *filedata = [NSData Datawithcontentsoffile:filepath];        Nserror *error = nil;        NSLog (@ "aa%@", FilePath); Self.audioplayer = [[Avaudioplayer alloc] Initwithdata:filedata error:&error];                        if (self.audioplayer! = nil) {self.audioPlayer.delegate = self;            [Self.audioplayer setnumberofloops:-1]; if ([Self.audioplayer preparetoplay] && [Self.audioplayer Play]) {NSLog (@ "successfully started play            ing ... "); } else {NSLog (@ "Failed to play.");}} else {NSLog (@ "Failed to play.");});

Description: The Love.wav file is a file under other sources.

Then modify the APPDELEGATE.M file, new method:

Java code
  1. -(void) Applicationdidenterbackground: (uiapplication *) application{
  2. [Nsrunloop Currentrunloop];
  3. //
  4. UIApplication *app=[uiapplication Sharedapplication];
  5. __block Uibackgroundtaskidentifier Bgtask;
  6. Bgtask=[app beginbackgroundtaskwithexpirationhandler:^{
  7. Dispatch_async (Dispatch_get_main_queue (), ^{
  8. if (bgtask!=uibackgroundtaskinvalid) {
  9. Bgtask=uibackgroundtaskinvalid;
  10. //            }
  11. //        });
  12. //    }];
  13. //
  14. Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
  15. Dispatch_async (Dispatch_get_main_queue (), ^{
  16. if (bgtask!=uibackgroundtaskinvalid) {
  17. Bgtask=uibackgroundtaskinvalid;
  18. //           }
  19. //       });
  20. //   });
  21. //
  22. [[UIApplication sharedapplication] setkeepalivetimeout:600 handler:^{
  23. NSLog (@ "KeepAlive");
  24. //    }];
  25. Mainviewcontroller *mvc=[[mainviewcontroller alloc] init];
  26. [MVC viewdidload];
  27. }
-(void) Applicationdidenterbackground: (uiapplication *) application{//[Nsrunloop currentrunloop];////uiapplication *app=[uiapplication sharedapplication];//__block UIBackgroundTaskIdentifier bgtask;//Bgtask=[app beginbackgroundtaskwithexpirationhandler:^{//Dispatch_async (Dispatch_get_main_queue (), ^{        if (bgtask!=uibackgroundtaskinvalid) {//bgtask=uibackgroundtaskinvalid;//}// });//}];////Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{//dispatch_ Async (Dispatch_get_main_queue (), ^{//if (bgtask!=uibackgroundtaskinvalid) {//BGTASK=UIBACKGROUNDTA skinvalid;//}//});///[[UIApplication sharedapplication] setkeepalivetimeout:600 Handler    : ^{//NSLog (@ "KeepAlive");/}];    Mainviewcontroller *mvc=[[mainviewcontroller alloc] init]; [MVC viewdidload];} 

There are also many online, found under the simulator can be long-running, but under the real-time machine does not run. Find it a bit better to play a silent audio file for a long time.

-------------------If there is any bad place, please advise.

PhoneGap iOS plugin development and unlimited background operation solution

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.