[Turn]ios hybrid APP implementation principle and performance monitoring

Source: Internet
Author: User

Transferred from: http://www.cocoachina.com/ios/20151118/14270.html

Implementation principle and performance monitoring of IOS hybrid APP2015-11-18 11:39 Edit: Lansekuangtu Category: iOS development Source: Cocoachina 1 2571

iOS principles hybrid App performance monitoring

author Dong Yifan Readme: as a ten-year code programmer, my best domain is the mobile platform of the client development, in the mobile field of development time more than seven years, and went through a lot of platforms. As most mobile platforms themselves die, now I'm focused on both iOS and Android mobile platforms, and occasionally in Windows, a platform that doesn't know whether to move or desktop. Ten years ago, when I first started, I thought I would always be a C + + programmer and spent a lot of time on C + +. Now C + + is one of the main languages I use to work, and I will occasionally write something to entertain myself. Write a few years after the program, and finally realized the narrow positioning, so began to learn a wide range of technology, a variety of language also learned a lot, fortunately, years of tossing down, I have not been to write code this thing is tired, so I think I will always do the development. Now, I also feel that development is a career that can be done for life, but in addition to the cause I want to pursue more things, from these years of experience, which throughout is constantly learning, to understand this point, I began in addition to the technology of the wider field of study, such as Japanese, painting, design, piano and so on, Positioning yourself has also become a lifelong learner in the future.

A simple introduction to IOS hybrid APP

Everyone should know that there are two kinds of portals on IOS devices, one is to download apps via App Strore and the other is to use a system browser to access the Web pages. The former is commonly referred to as native application, the latter being the traditional Web page. Each has its own characteristics, developing a native application, typically using the development tools and COCOA framework that Apple provides to us. The advantage is that you can take advantage of all the features of the system, make cool features without losing any performance, and the downside is that every time the app offers new features you have to repackage the app, submit it to Apple for review, and then upgrade it on an average of two weeks after the app Store. On the contrary, write a Web page does not have this limit, the server to do an upgrade, the user through the browser again access, is the latest, and the shortcomings of the Web page is subject to a lot of limitations, many system features are inaccessible, and performance is often not high, so it is difficult to achieve some cool effect.

Given the advantages of native apps and Web pages, a hybrid application (hybrid app) is developed in a way that is in between. It is characterized by embedding a browser component in the native application, and then somehow allowing the native code and the Web page to communicate in two directions, with the result that native functionality can be used when native functionality is needed, and that the parts that fit on the web side are placed on the server. To some extent, the advantages of both are exploited. Another advantage is that because Web technology is the same on IOS and Android, this part of the page is naturally cross-platform.

Two how to implement hybrid APP

The simplest way to implement a hybrid App is to use the Apache Cordova Open source framework. Cordova has helped you do all the bridging between the web and native apps, and all you have to do is write the corresponding page code and native code according to his documents. Please refer to the official website for details.

Unfortunately, there are some scenarios where we can't use Cordava, such as one of my projects, where the main project is to provide an SDK, and the SDK itself uses hybrid technology. However, the SDK users may also use Cordova, in some cases, the Cordova for the two are different versions, just not compatible. So you need to implement the bottom of the hybrid App yourself.

The bottom-up implementation of the three IOS hybrid App

1. JavaScript functions in native code calls on Web pages

Suppose we have the following code in our web page

12345 [script type="text/javascript"]    functionmyFunc() {        return"Text from web"    }[/script]

Native code can call MyFunc () in the following way

1 NSString * result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc()"];

Here the result is equal to the Text from web

2. JavaScript in the Web page calls the system's native code

This is a bit more complicated than the above, and IOS does not like Android to inject a native code interface directly into JavaScript functions in a Web page. Here we will use a more tortuous way to achieve.

Suppose there is a method in the Objective-c class

12 -(void)nativeFunction:(NSString*)args {}

In JavaScript, we use the method below to finally call the method above.

1 window.JSBridge.callFunction("callNativeFunction""some data");

In our page, there is no jsbridge.callfunction exist, this step we have to inject on the native code side.

In WebView's delegate-(void) Webviewdidfinishload: (UIWebView *) WebView we inject JavaScript in the following way

1234567891011121314151617181920 NSString *js = @"(function() {\window.JSBridge = {};\window.JSBridge.callFunction = function(functionName, args){\varurl = \"bridge-js://invoke?\";\varcallInfo = {};\callInfo.functionname = functionName;\if(args)\{\callInfo.args = args;\}\url += JSON.stringify(callInfo);\var rootElm = document.documentElement;\variFrame = document.createElement(\"IFRAME\");\iFrame.setAttribute(\"src\",url);\rootElm.appendChild(iFrame);\iFrame.parentNode.removeChild(iFrame);\};\returntrue;\})();";[webView stringByEvaluatingJavaScriptFromString:js];

To explain briefly, first we create an object called Jsbridge in the window, and then define a method callfunction inside, which is the function of packaging two parameters into a JSON string, and then comes with our custom URL bridge-js:// Invoke? Back, and finally the URL is loaded with an IFRAME

The reason for this is that when the IFRAME is loaded, it calls WebView's delegate-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: ( Nsurlrequest *) Request Navigationtype: (Uiwebviewnavigationtype) Navigationtype method, where request is the URL we just customized, In this method we do the following

123 NSURL *url = [request URL];NSString *urlStr = url.absoluteString;return[self processURL:urlStr];

The Processurl function is as follows

12345678910111213141516171819202122 -(BOOL) processURL:(NSString *) url{    NSString *urlStr = [NSString stringWithString:url];    NSString *protocolPrefix = @"bridge-js://invoke?";    if([[urlStr lowercaseString] hasPrefix:protocolPrefix])    {        urlStr = [urlStr substringFromIndex:protocolPrefix.length];        urlStr = [urlStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];        NSError *jsonError;        NSDictionary *callInfo = [NSJSONSerialization                                JSONObjectWithData:[urlStr dataUsingEncoding:NSUTF8StringEncoding]                                options:kNilOptions                                error:&jsonError];        NSString *functionName = [callInfo objectForKey:@"functionname"];        NSString * args = [callInfo objectForKey:@"args"];        if([functionName isEqualToString:@"callNativeFunction"]) {            [self nativeFunction:args];        }        returnNO;    }    returnYES;}

From Bridge-js://invoke? This custom URL inside the JSON string is included in the parse out, and then determine the value of functionname key if it is callnativefunction then call the native method nativefunction, if you need to implement more method calls, Just add this mapping relationship.

The two-way invocation of JavaScript and OBJECTIVE-C code is now implemented.

Four performance monitoring

The debate between Hybrid and native applications has been a lot, and the core issue is how to balance the relationship between development cost and user experience. The development cost of hybrid is generally lower than the native application, and the experience is always worse. Performance monitoring is even more important to make Hybrid's user experience more likely to be closer to native applications.

There are two main areas that affect the APP experience in general

The first aspect is the responsiveness of the UI, the smoothness of the UI or the user experience is very different. In this aspect of performance monitoring, the general practice is to play a timestamp in the main interaction function, and for the system View, you can also use method Swizzle to all the system functions of the call time statistics.

The second is the network, and because most of the apps now have network requests, the request speed of the network will affect the user experience to a great extent. The network problem is more obvious in the Hybrid App. Hybrid App will always go to load server-side page, before the page load out, it is likely that the entire phone screen is blank, if the blank time is too long, it will be a bad thing, so real-time monitoring the time of the request page, as well as the loading speed of the page is very necessary. For WebView, it is recommended to make a timestamp in several of its delegate methods to count the time of page requests and loading.

In short, it's not a very complicated job to achieve. However, performance monitoring work, implementation is just one of the aspects, due to the user's habits, the actual network environment of various problems, performance monitoring is not in the development phase of monitoring, in general, always have to deploy monitoring to end-user mobile phone up, if it is a user-volume App, So how to collect a lot of data good statistics show, this is entirely another matter, to do this, to involve a lot of data organization, front-end display of the work, the actual implementation is definitely not a simple job.

Fortunately, there are many companies that have helped us with this work, such as New Relic,app Dynamics,compuware, listening to the cloud and so on. This time, let's take a look at the cloud as an example of how they did the performance monitoring thing.

Five-listen cloud Probe (IOS app edition) use

Listening to the cloud APP performance monitoring is still relatively simple to use, the simple steps are as follows

After applying for the cloud account, fill in the relevant information where you added the APP

Then you'll get a unique App Key.

Then download the Framework of the IOS SDK to listen to the cloud, copy to the project, and add the following 4 additional system libraries

    • Coretelephony.framework

    • Security.framework

    • Systemconfiguration.framework

    • Libz.dylib

Then include the header file in the app's PCH file that listens to the cloud app probe

1 #import

Finally, add the MAIN.M

1 [NBSAppAgent startWithAppID:App_Key];

The code generally looks like the bottom

123456 int main(int argc, char * argv[]) {@autoreleasepool {    [NBSAppAgent startWithAppID:App_Key];    returnUIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));    }}

So the whole integration work is done. Launches the APP, indicating that the code integration is successful if the following is displayed in the log logs

123 NBSAppAgent 2.2.2.1---->start!Success to connect to NBSSERVER

Observation of six listening cloud monitoring data

1. Summarize data

Login to the Background management page of the cloud, first we can see the aggregated monitoring data, the effect of the chart is good, the mouse on each data point will show detailed data.

In general, there are two broad categories, one is application interaction performance, which is mainly to monitor the UI response, give the view load, and the layout of the time summary. If you find an exception to an argument, it might be a signal to refactor the UI. The other is network performance, including the response time of network requests.

2. Web View

The important thing to say first is that this part is the most distinctive part of listening to the cloud at the moment (as if it were the first to do so, not yet seen in other similar services). Usually when we conduct network performance monitoring, given is the entire network request situation, which in the browser, the entire network request is actually the page request, there is no difference between the two. In the APP, it's also an HTTP request, either from a Web service or from a Web view load page. And the latter happens to be the main implementation of the Hybrid App we're talking about. This entry to the cloud is simply a request for a Web view, in other words, the best data we can use to monitor the performance of the Hybrid APP network.

(1) HTTP request

Here is the summary data for all pages loaded by the Web view.

(2) Page loading

Listen to the cloud in addition to the network performance data, here is also very thoughtful to give the page load summary data, to know that the current page is likely to be very complex, contains a lot of page elements, the desktop problem may not be obvious, but on the mobile side, too complex effect may be greatly slow loading speed, affecting the user experience. Based on the page load data here, you can have targeted to optimize the page.

3. Network

This entry is primarily data for all Web requests from the APP.

(1) Map of extension and complement

This is primarily a subtotal data that allows you to view aggregated data for your own APP and for network requests sent by a third-party service.

(2) HTTP request

As the name implies, this is the detailed data for all HTTP requests, showing the slowest-responding hosts, and the highest-throughput hosts, respectively.

(3) Regional

This article is more interesting, the color of the way to mark the world's average response time, click the corresponding country can continue to enter the next level, finally can go to the detailed web data analysis page.

(4) Combinatorial analysis

This page in China's network environment is very useful, it can be based on the operator, region, access to the method to give summary data. To know that China's network environment is very complex, different operators, and even the same operators in different areas of the network interoperability will be very large. With the data here, you can deploy the server in a targeted way to optimize the network experience.

4. Interaction

Enter an interactive analysis specific item

Here we can see in detail the Viewcontroller and the View of each system function call time, through this data can be very good analysis of which one viewcontroller out the problem, corresponding to the refactoring can be.

Interactive analysis of the following is a certain condition of the UI interaction of the specific data, can be filtered through the version, so it is convenient to filter out the problem has been modified out of the version. You can also view the data for each interaction response through the operating system (ios/android) and the device.

5. Other

In addition to performance analysis, there are common crash data, active numbers, and event monitoring in the cloud-listening data. There's no detail here.

Vii. Summary

The Hybrid App is very useful in certain scenarios, but it does have its limitations, especially where it is highly interactive, and it is not appropriate to use it, after all, it is based on web technology. But HTML5 in the mobile side of the development is very fast, perhaps there will be a better future is probably. In short, mastering this technology is not wrong. In addition, since the Web site is likely to become a bottleneck for our performance, we should always pay attention to the performance of the relevant parts of the test, but also recommend the use of some of the third-party application performance monitoring services. This can better locate the problem of the product environment.

[Turn]ios hybrid APP implementation principle and performance monitoring

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.