Use iOS-oriented local plug-in extension

Source: Internet
Author: User
Tags creative commons attribution string back

This article discusses in detail the native plug-in of the PhoneGap (also known as Apache Cordova) Application in Xcode (targeting iOS devices. If you are new to PhoneGap or want to review the basic knowledge of PhoneGap, read the PhoneGap entry for Xcode for iOS before continuing to read this article.

This document uses terminologies AlternatelyCordovaAndPhoneGapIndicates the same open-source application platform that allows you to use HTML and JavaScript to create mobile applications installed locally. The PhoneGap code base has been migrated to the open resource of the Apache Software Foundation, named Cordova. Adobe still uses the PhoneGap name for distribution. For more information, see the blog post "PhoneGap, Cordova, and name" published by Brian Leroux ?" As Brian said in this article, "the only difference currently is that the names of downloaded packages are different, and this situation will remain for a while.

PhoneGap not only allows you to use Web technology to build user interfaces for mobile applications installed on your local machine, but also provides JavaScript-Based APIS for you to interact with the functions of your local device. By default, PhoneGap can access the media replay between the camera, accelerator, file system, GPS location, and other functions of the device. However, PhoneGap does not reveal every native API that you can use in JavaScript applications. If you want PhoneGap to perform operations other than its default feature set, you can use the PhoneGap native plug-in model to extend the features of the core PhoneGap API.

The native plug-ins of PhoneGap are different from those of the desktop browser. They provide you with a plug-in custom code to add the PhoneGap application framework function. The PhoneGap native plug-in allows you to create new custom functions in the form of native code and display them to the PhoneGap application through the native-JavaScript Bridge of PhoneGap. This means that you can display all the libraries or frameworks for use within a JavaScript-based PhoneGap application.

Understand the structure of the native plug-in of PhoneGap

Before writing a native PhoneGap plug-in, it is helpful to understand how the PhoneGap application container displays the native operating system functions to JavaScript-based applications.

All Cordova APIs contain the following two components: a JavaScript-based interface that can be accessed within your application, and the corresponding local class used to perform operations with local code. Generally, JavaScript classes and local classes have APIs that mirror each other, so that tracing can be easily performed. JavaScript usageCordova.exec()Function calls the local code. When it callsCordova.execYou can pass it to the result handler function and error handler function, and also pass a set of parameters to the local code, and pass the reference to the local class name and the local function name. Cordova will be responsible for managing the communication between JavaScript and the local machine, and you can concentrate on building your own applications.

To learn more about the native plug-in of PhoneGap, log on to Cordova wiki to view the source code of this core API. The entire PhoneGap framework is built on the same mode. You can learn about this mode here.

Build the first plug-in

To start building your first PhoneGap plug-in, follow the steps described in Xcode for iOS's PhoneGap getting started to create a new PhoneGap project. I named my project MyFirstPhoneGapNativePlugin.

JavaScript

After setting the Hello Xcode project, you can prepare to create a JavaScript interface for the local plug-in. You need to create a class using a function (the logic to display the image through the local code. In the www folder, create a JavaScript file named HelloPlugin. js, which contains the simple JavaScript class shown below.

var HelloPlugin = { callNativeFunction: function (success, fail, resultType) { return Cordova.exec( success, fail, "com.tricedesigns.HelloPlugin", "nativeFunction", [resultType]); } };

The HelloPlugin class containscallNativeFunctionIt receives a successful callback function, an error callback function, andresultTypeString parameter.callNativeFunctionFunction inclusionCordova.execFunction, so the actual local code will be called. There is no other JavaScript in this class, but you can add JavaScript code here as needed.

CallCordova.execYou will see the following five parameters:

  • A successful callback function (the function called when the Code layer of the Local Machine responds successfully) References
  • An error callback function (the function called when an error response occurs at the local code layer)
  • A local code string reference (I will introduce it in detail below)
  • A function name string reference that should be called
  • An array of parameters to be passed to the local code

Remember that the code execution operations between JavaScript and the native code layer are not synchronized. Therefore, you must use callback functions and asynchronous coding practices when developing the native PhoneGap plug-in.

Local class

To create a native code layer, first create a new Native Objective-C class that extends the CDVPlugin class of core Cordova APIs:

Figure 1. Create a new file.

  1. In the New File wizard, select the Objective-C class template and click Next (see figure 2 ).

Figure 2. Select the Object-C class template.

  1. TypeHelloPluginAs the name of the new class, and add the class as a subclass of CDVPlugin (see figure 3 ).

Figure 3. Name the class.

The CDVPlugin class is the parent class that must be extended by all Cordova classes. The CDVPlugin class uses the PhoneGAP API to encapsulate all the necessary logic required for local JavaScript communication.PhoneGap.execFunction allows you to call functions in the new class. The CDVPlugin class containswriteJavascriptAllows you to call JavaScript in the Web View of the PhoneGap application. All communication from the local machine to Web JavaScript must be performedwriteJavascriptFunction completed.

  1. Click Next.
  2. After the prompt appears, specify a location for the new file (preferably in the Plugins directory of the Xcode project), and click Finish to continue the operation.

You will see a new header file (. h) and a new implementation file (. m) in the PhoneGap project (see figure 4 ).

Figure 4. New local class file.

  1. Next, in your. h filenativeFunctionAdd a function definition. For example:

#import <Cordova/CDV.h> @interface HelloPlugin : CDVPlugin - (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options; @end

This definition contains the following two parameters:NSMutableArrayContains parameters received from the JavaScript layer and the option Dictionary (MAP. In this example, you only need to pay attention to the parameter array. The header file only contains the method signature. You do not need to include any application logic in the. h file.

  1. After you create a class signature, add the logic to the. m filenativeFunctionFunction instance. The following shows an example of the Objective-C function used inside the local plug-in class.

#import "HelloPlugin.h" @implementation HelloPlugin - (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options { //get the callback id NSString *callbackId = [arguments pop]; NSLog(@"Hello, this is a native function called from PhoneGap/Cordova!"); NSString *resultType = [arguments objectAtIndex:0]; CDVPluginResult *result; if ( [resultType isEqualToString:@"success"] ) { result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @"Success :)"]; [self writeJavascript:[result toSuccessCallbackString:callbackId]]; } else { result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString: @"Error :("]; [self writeJavascript:[result toErrorCallbackString:callbackId]]; } } @end

InnativeFunctionYou must first obtain an NSStringcallbackIdThe core PhoneGap API maps the response of this function to the original JavaScript that calls this function.

Next, use this methodNSLogWrite the message to the Xcode debugging console; this only indicates that it is currently executing the local code.

After being written to the debugging console, the function will checkresultTypeAnd then create the correspondingCDVPluginResultInstance.resultTypeThe value is a simple string. IfresultTypeYessuccess", The function will be createdSuccessAnd use[self writeJavascript]The function writes the successful callback function to the JavaScript layer. Any otherresultTypeAll parameter values are generated.ErrorResult, and the function writes the error callback to the JavaScript layer.

When you write the success or error callback function back to JavaScript, you always use the CDVPluginResult instance. However, you can also usewriteJavascriptThe function passes any JavaScript string back to the JavaScript layer. This technology can even be used to push data from the local layer to the JavaScript layer in real time.

Call plug-ins

Since you have created a plug-in, you can call it within the PhoneGap application.

<script type="text/javascript" charset="utf-8" src="HelloPlugin.js"></script>

  1. Also inonDeviceReady()Function, add JavaScript to call the local plug-in and process the plug-in results. Add namecallNativePlugin,nativePluginResultHandlerAndnativePluginErrorHandlerAs follows:

function callNativePlugin( returnSuccess ) { HelloPlugin.callNativeFunction( nativePluginResultHandler, nativePluginErrorHandler, returnSuccess ); } function nativePluginResultHandler (result) { alert("SUCCESS: \r\n"+result ); } function nativePluginErrorHandler (error) { alert("ERROR: \r\n"+error ); }

  1. callNativePluginThe function only needs to call the JavaScript native plug-in class interface. When it callscallNativeFunctionThe success and error status callback functions received from the local code layer are passed. If the local layer returns the callback function successfully, it will callnativePluginResultHandlerFunction, which is called when the local layer returns an error callback.nativePluginErrorHandlerFunction.
  1. Next, add two JavaScript buttons according to the following code to call the plug-in.

<body onload="onBodyLoad()">

Click the first button to callcallNativeFunctionAnd generate the "success" parameter ". PhoneGap will then execute the local code and call back successfully at the JavaScript layer (it will callnativePluginResultHandlerFunction ).

When you click the second buttoncallNativeFunctionAnd generate the parameter "error ". PhoneGap will execute the local code and call the error callback at the JavaScript layer (it will callnativePluginErrorHandlerFunction ).

Ing local code class

At this point, you have connected almost all things and are ready to execute the operation, but you must complete another step to call the local code in JavaScript.

You must add a ing so that Cordova can recognize your native code class. Remember to callCordova.execIs it used to identify the string reference of the local class? You need to map the string to the actual class instance in the Cordova. plist file. The Cordova. plist file contains all the configuration information of the current Cordova project.

KeyYesPhoneGap.execMaps to the unique string reference used by the local code class.ValueIs the name of the actual local class to be called.

  1. Save the changes.

Figure 5. Edit Cordova. plist.

Now, you can start the application and perform a thorough check.

To start the application, click the Run button or choose Product> Run.

After the application is started in iOS Simulator (or on a connected device), you will see a simple interface with two buttons (see figure 6 ). Click any button to call the local code of the local plug-in. A warning message is displayed through JavaScript no matter whether the call is successful or the error callback is successful.

Figure 6. Applications running in the iOS simulator.

When calling the local code, you can also see the output in the Xcode debugging Console window, reflecting the call to the local plug-inNSLogOutput content (see figure 7 ).

Figure 7. record information of the Xcode debugging console.

Next reading

Now you know how to create a native plug-in for the PhoneGap application on iOS devices. You can use this technology to access the iOS framework not displayed by the core PhoneGap SDK, including (but not limited to) the game center, core audio and Bonjour framework, or any other local code. At the same time, do not forget to check a large number of existing GitHub PhoneGap native plug-ins developed by the open-source community.

+

This product is licensed by Creative Commons Attribution-nonequalcial-Share Alike 3.0 Unported License. Adobe provides permissions beyond the permitted scope related to the code examples included in this product.

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.