APM for iOS Apps
Tags: ios, huawei, apm
Published: 2022-03-10 10:16:05

**Introduction**

**Overview**

App Performance Management (APM) provides minute-level app performance monitoring capabilities. You can view and analyze app performance data that APM collects, to gain a clear understanding of real-time online app performance, helping you quickly and accurately rectify app performance problems and enhance user experience.

**What You Will Create**

In this codelab, you will build an app that integrates APM, manually trigger a network request to test the APM service, and learn how to view and analyze app performance problems with APM.
During app development and debugging, you may need to disable APM performance monitoring, which can be done (or re-enabled) by Remote Configuration. Moreover, the APM SDK provides a performance collection API allowing users to determine whether they can enable the APM performance monitoring function in the app.

**What You Will Learn**

In this codelab, you will learn how to:

- Integrate APM into your app.
- View and analyze app performance data on the APM page in AppGallery Connect.
- Enable and disable APM performance monitoring.

**What You Will Need**

Development Environment Requirements

- Mac with Xcode 10.1 or later installed
- CocoaPods 1.4.0 or later installed
- [A HUAWEI ID](https://developer.huawei.com/consumer/en/doc/start/registration-and-verification-0000001053628148), whose identity has been verified

**Device Requirements**

- An iPhone or a simulator for testing

**Integration Preparations**

Before integrating APM, you must complete the following:

- Create a project in AppGallery Connect.
- Add an app to your project.
- Create an Xcode project.
- Integrate the SDK into your Xcode project.

**Note**: You need to register as a developer to complete the operations above.

**Configuring the Development Environment**

#####Enabling HUAWEI Analytics

The APM service uses [HUAWEI Analytics](https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/79044452) to report performance management events. Therefore, you must enable HUAWEI Analytics before integrating the APM SDK.

#####Integrating the Service SDK

If you are using Xcode, you need to integrate the APM SDK into your Xcode project with CocoaPods.

1) Add the configuration file in AppGallery Connect to your Xcode project.

- Sign in to AppGallery Connect and click My projects.
- Click your project card and select an app to be integrated from the app drop-down list on the top.
- Go to Project settings > General information and download agconnect-services.plist under App information.
- Copy the agconnect-services.plist file to your app's root directory.

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8revpcez9939zk8wmctb.png)

2) Create a Podfile.

Open the CLI and navigate to the location of the Xcode project. Then, create a Podfile. Skip this step if a Podfile already exists.

```
cd project-directory
pod init
```

3) Edit the Podfile.

- Integrate the Analytics SDK, APM SDK, and Remote Configuration SDK.
Edit the Podfile to add pod dependencies of the Analytics SDK, AppGallery Connect SDK, APM SDK, and Remote Configuration SDK.

```
target 'apmIOSDemo' do
   pod 'AGConnectCore'
    pod 'AGConnectRemoteConfig'
    pod 'HiAnalytics', '~> 5.0.4.23'
    pod 'AGConnectAPM'
end
```

- Install the pod and open the .xcworkspace file to view the project.

```
pod install
```

**Designing the UI**

You can create a page in your Xcode project and design the UI according to the following figure. Only three buttons are needed: one for initiating a network request, one for disabling APM, and the last one for enabling APM.

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c5isc9uy7318ookixacn.png)

**Reporting Network Events**

You can manually add a time-consuming cyclic log recording operation to trigger a network request, and check whether the launch duration and network performance indicators on the APM page are normal. App launch and screen events are automatically reported when the app is launched. The procedure is as follows: 

1) Initialize the AppGallery Connect SDK, import the header file to the AppDelegate.m file of the project, and add the initialization code. Add a time-consuming cyclic log recording operation, and change the number of cycles while monitoring changes to the launch duration.

```
#import "AppDelegate.h"
#import <AGConnectCore/AGConnectCore.h>
@implementation AppDelegate
- (BOOL)Application:(UIApplication *)Application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override the code for customization after the app launch.
[AGCInstance startup];// Initialization.
long sum = 0;
for (int i = 0; i < 9999; i++) {
sum = sum + i;
NSLog(@"sum=%ld",sum);
}
return YES;
}
…
@end
```
2) Create a **Send Network Request** test button in **ViewController** in your app. You can tap the button to call **sendNetworkRequest** to trigger a network request event.

```
#import "ViewController.h"
#import "AGConnectAPM/AGConnectAPM.H"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton* sendNetworkRequestBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
sendNetworkRequestBtn.frame = CGRectMake(80, 100, 200, 40);
[sendNetworkRequestBtn setTitle:@"Send Network Request" forState:UIControlStateNormal];
[sendNetworkRequestBtn addTarget:self action:@selector(sendNetworkRequest) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sendNetworkRequestBtn];
}
- (void)sendNetworkRequest {
NSURL *url = [NSURL URLWithString:@"https://developer.huawei.com/consumer/cn/"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result: %@", str);
}];
[task resume];
}
…
@end
```

**Enabling/Disabling Performance Data Collection**

1) Create an APM Collection Off test button in ViewController in your app. You can tap the button to call the enableCollection method to disable APM.

```
#import "ViewController.h"
#import "AGConnectAPM/AGConnectAPM.H"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton* disableBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
disableBtn.frame = CGRectMake(80, 150, 200, 40);
[disableBtn setTitle:@"APM Collection Off" forState:UIControlStateNormal];
[disableBtn addTarget:self action:@selector(disableCollection) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:disableBtn];
}
- (void)disableCollection {
[[AGCAPM sharedInstance] enableCollection:NO];// Disable APM.
}
…
@end
```

2) Create an **APM Collection On** test button in **ViewController** in your app. You can tap the button to call the **enableCollection** method to enable APM.

```
- (void)enableCollection {
[[AGCAPM sharedInstance] enableCollection:YES];// Enable APM.
}
```

**Viewing and Analyzing App Performance Data**

1) Sign in to [AppGallery Connect](https://developer.huawei.com/consumer/en/service/josp/agc/index.html#/) and click **My projects**.

2) Click your project card and select your app from the app drop-down list at the top.

3) Go to **Quality > APM**. Click **Overview**. The overview presents indicators including the launch duration (by version), slow frame rate (top 5 view controllers), frozen frame rate (top 5 view controllers), network request duration (top 5 countries/regions), and network request success rate (trend over time).

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dysdbbzh5dxqa2sw4srr.png)

4) Go to **App analysis > App launch duration**.

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0p12pxhpnnuxj2nkeky2.png)

5) Click **View details** to bring up the app launch duration details page.

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v86ti3xg381jt7lmtnbc.png)

6) (Optional) Select Modify threshold, set the threshold, and then click Ok.

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wc1btqb836594ta3f7xe.png)

7) Go to App analysis > Native page rendering to view details about the page freezing information (corresponding to ViewController), and then make optimizations accordingly.

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fdt5q1obcu5nscv037q.png)

**Disabling APM**

1) Method 1: You can disable APM for a released app on the cloud. On the App performance management page, click the Configuration tab and find Overall switch. Then, disable the switch.

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l6gv6pbf3psecqjuexf8.png)
2) Method 2: You can disable the performance data reporting function for some versions. On the App performance management page, click the Configuration tab and find Version blocklist settings. Click Add to add the disabled version number to the list.

![Image descriptio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3xoobqkw15na3h7z8n7w.png)

3) Method 3: If your app allows users to enable or disable performance monitoring, use the method provided by the APM SDK. Call **getInstance** for initialization and call **enableCollection** to enable or disable performance monitoring. Performance monitoring in apps will be disabled where applicable. If users disable performance monitoring in apps, APM will not collect performance data even if the performance monitoring function is enabled through Remote Configuration in AppGallery Connect.

**Congratulations**

Well done. You have successfully created an app with APM integrated, and learned how to view and analyze app performance data. You can also disable or enable APM as needed.

**References**

API reference
Sample code