Giter Club home page Giter Club logo

applicationinsights-ios's Introduction

Build Status

Application Insights for iOS (1.0-beta.8) DEPRECATED

This SDK is officially deprecated. Please switch to HockeyApp or consider MobileCenter.

You can find more about the transition from Application Insights to HockeyApp here and about how Mobile Center will be the future of HockeyApp here.

Please don't hesitate to get in touch via [email protected] if you have questions.

About

=======

This is the repository of the iOS SDK for Application Insights. Application Insights is a service that monitors the performance and usage of your published app. The SDK enables you to send telemetry of various kinds (events, traces, sessions etc.) to the Application Insights service where your data can be visualized in the Azure Portal.

You can use the Application Insights for Mac tool to integrate the Application Insights iOS SDK into your existing apps. The SDK runs on devices with iOS 6.0 or higher. You'll need a subscription to Microsoft Azure. (It's free until you want to send quite a lot of telemetry.)

Application Insights overview

##Breaking Changes!

Version 1.0-beta.8 of the Application Insights for iOS SDK comes with two major changes:

Crash Reporting and the API to send handled exceptions have been removed from the SDK. In addition, the Application Insights for iOS SDK is now deprecated.

The reason for this is that HockeyApp is now our major offering for mobile and cross-plattform crash reporting, beta distribution and user feedback. We are focusing all our efforts on enhancing the HockeySDK and adding telemetry features to make HockeyApp the best platform to build awesome apps. We've launched HockeyApp Preseason so you can try all the new bits yourself, including User Metrics.

We apologize for any inconvenience and please feel free to contact us at any time.

Content

  1. Release Notes
  2. Requirements
  3. Setup
  4. Advanced Setup
  5. Developer Mode
  6. Basic Usage
  7. Advanced Usage
  8. Automatic collection of life-cycle events
  9. Set Custom Server Endpoint
  10. Documentation
  11. Contributing
  12. Contact

1. Release Notes

  • Remove crash reporting. To add this feature to your app, we recommend to use HockeyApp which provides you with superior crash reporting, feedback, beta distribution and much more.
  • Enable Bitcode. This was previously not possible as Bitcode-enabled apps are recompiled at unknown times on Apple's servers and make it very hard to get fully symbolicated and useful crash reports.
  • Fixes an issue where pageview durations where incorrectly sent as days instead of as a string in the 'd:hh:mm:ss.fffffff' format. The relevant methods now take an NSTimeInterval parameter with the duration in seconds.

See here for the release notes of previous versions.

2. Requirements

The SDK runs on devices with iOS 6.0 or higher.

3. Setup

We recommend integration of our binary into your Xcode project to setup Application Insights for your iOS app. For other ways to setup the SDK, see Advanced Setup.

You can use the Application Insights for Mac tool to integrate the SDK, which provides you with a step-by-step wizard for this process. If you want to integrate the SDK manually, you can do that by following this steps:

3.1 Obtain an Instrumentation Key

To view your telemetry, you'll need an Application Insights resource in the Microsoft Azure Portal. You can either:

Open your resource and open the Essentials drop-down. Shortly, you'll need to copy the Instrumentation Key.

3.2 Download the SDK

  1. Download the latest Application Insights for iOS framework which is provided as a zip-File.
  2. Unzip the file and you will see a folder called ApplicationInsights .

3.3 Copy the SDK into your projects directory in Finder

From our experience, 3rd-party libraries usually reside inside a subdirectory (let's call our subdirectory Vendor), so if you don't have your project organized with a subdirectory for libraries, now would be a great start for it. To continue our example, create a folder called "Vendor" inside your project directory and move the unzipped ApplicationInsights-folder into it.

3.4 Set up the SDK in Xcode

  1. We recommend to use Xcode's group-feature to create a group for 3rd-party-libraries sixmilar to the structure of our files on disk. For example, similar to the file structure in 4.3 above, our projects have a group called Vendor.
  2. Make sure the Project Navigator is visible (⌘+1)
  3. Drag & drop ApplicationInsights.framework from your window in the Finder into your project in Xcode and move it to the desired location in the Project Navigator (e.g. into the group called Vendor)
  4. A popup will appear. Select Create groups for any added folders and set the checkmark for your target. Then click Finish.
  5. Open the Info.plist of your app target and add a new field of type String. Name it MSAIInstrumentationKey and set your Application Insights instrumentation key from 4.1 as its value.
### 3.5 Modify Code

Objective-C

  1. Open your AppDelegate.m file.

  2. Add the following line at the top of the file below your own import statements:

    @import ApplicationInsights;
  3. Search for the method application:didFinishLaunchingWithOptions:

  4. Add the following lines to setup and start the Application Insights SDK:

    [[MSAIApplicationInsights sharedInstance] setup];
    // Do some additional configuration if needed here
    //... more of your other setup code here ...
    [[MSAIApplicationInsights sharedInstance] start];

    You can also use the following shortcuts:

    [MSAIApplicationInsights setup];
    [MSAIApplicationInsights start];

Swift

  1. Open your AppDelegate.swift file.

  2. Add the following line at the top of the file below your own import statements:

    import ApplicationInsights
  3. Search for the method

    application(application: UIApplication, didFinishLaunchingWithOptions launchOptions:[NSObject: AnyObject]?) -> Bool`
  4. Add the following lines to setup and start the Application Insights SDK:

    MSAIApplicationInsights.sharedInstance().setup();
    MSAIApplicationInsights.sharedInstance().start();

    You can also use the following shortcuts:

    MSAIApplicationInsights.setup()
    MSAIApplicationInsights.start()

Congratulation, now you're all set to use Application Insights! See Basic Usage on how to use Application Insights.

4. Advanced Setup

4.1 Set Instrumentation Key in Code

It is also possible to set the instrumentation key of your app in code. This will override the one you might have set in your Info.plist. To set it in code, MSAIApplicationInsights provides an overloaded constructor:

[MSAIApplicationInsights setupWithInstrumentationKey:@"{YOUR-INSTRUMENTATIONKEY}"];

//Do additional configuration

[MSAIApplicationInsights start];
### 4.2 Linking System Frameworks manually

If you are working with an older project which doesn't support clang modules yet or you for some reason turned off the Enable Modules (C and Objective-C and Link Frameworks Automatically options in Xcode, you have to manually link some system frameworks:

  1. Select your project in the Project Navigator (⌘+1).
  2. Select your app target.
  3. Select the tab Build Phases.
  4. Expand Link Binary With Libraries.
  5. Add the following system frameworks, if they are missing:
    • CoreTelephony
    • Foundation
    • Security
    • SystemConfiguration
    • UIKit
    • libz

Note that this also means that you can't use the @import syntax mentioned in the Modify Code section but have to stick to the old #import <ApplicationInsights/ApplicationInsights.h>.

4.3 Setup with CocoaPods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like ApplicationInsights in your projects. To learn how to setup CocoaPods for your project, visit the official CocoaPods website.

[NOTE] When adding Application Insights to your podfile without specifying the version, pod install will throw an error because using a pre-release version of a pod has to be specified explicitly. As soon as Application Insights 1.0 is available, the version doesn't have to be specified in your podfile anymore.

Podfile

platform :ios, '8.0'
pod "ApplicationInsights", '1.0-beta.8'

4.4 iOS 8 Extensions

The following points need to be considered to use the Application Insights SDK with iOS 8 Extensions:

  1. Each extension is required to use the same values for version (CFBundleShortVersionString) and build number (CFBundleVersion) as the main app uses. (This is required only if you are using the same MSAIInstrumentationKey for your app and extensions).
  2. You need to make sure the SDK setup code is only invoked once. Since there is no applicationDidFinishLaunching: equivalent and viewDidLoad can run multiple times, you need to use a setup like the following example:
@interface TodayViewController () <NCWidgetProviding>
@property (nonatomic, assign) BOOL didSetupApplicationInsightsSDK;
@end

@implementation TodayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (!self.didSetupApplicationInsightsSDK) {
        [MSAIApplicationInsights setup];
        [MSAIApplicationInsights start];
        self.didSetupApplicationInsightsSDK = YES;
    }
}

4.5 WatchKit Extensions

WatchKit extensions don't use regular UIViewControllers but rather WKInterfaceController subclasses. These have a different lifecycle than you might be used to. To make sure that the Application Insights SDK is only instantiated once in the WatchKit extension's lifecycle we recommend using a helper class similar to this:

@import Foundation;

@interface MSAIWatchSDKSetup : NSObject

+ (void)setupApplicationInsightsIfNeeded;

@end
#import "MSAIWatchSDKSetup.h"
#import "ApplicationInsights.h"

static BOOL applicationInsightsIsSetup = NO;

@implementation MSAIWatchSDKSetup

+ (void)setupApplicationInsightsIfNeeded {
  if (!applicationInsightsIsSetup) {
    [MSAIApplicationInsights setup];
    [MSAIApplicationInsights start];
    applicationInsightsIsSetup = YES;
  }
}

@end

Then, in each of your WKInterfaceControllers where you want to use the Application Insights SDK, you should do this:

#import "InterfaceController.h"
#import "ApplicationInsights.h"
#import "MSAIWatchSDKSetup.h"

@implementation InterfaceController

- (void)awakeWithContext:(id)context {
  [super awakeWithContext:context];
  [MSAIWatchSDKSetup setupApplicationInsightsIfNeeded];
}

- (void)willActivate {
  [super willActivate];
}

- (void)didDeactivate {
  [super didDeactivate];
}

@end

5. Developer Mode

###5.1 Batching of data

The developer mode is enabled automatically in case the debugger is attached or if the app is running in the simulator. This will decrease the number of telemetry items sent in a batch (5 items) as well as the interval items when telemetry will be sent (3 seconds).

###5.2 Logging

We're all big fans of a clean debugging output without 3rd-party-SDKs messages piling up in the debugging view, right?! That's why Application Insights keeps log messages to a minimum (like critical errors) unless the developer specifically enables debug logging before starting the SDK:

[MSAIApplicationInsights setup]; //setup the SDK
 
[[MSAIApplicationInsights sharedInstance] setDebugLogEnabled:YES]; //enable debug logging 

[MSAIApplicationInsights start]; //start using the SDK

This setting is ignored if the app is running in an app store environment, so the user's console won't be littered with our log messages.

6. Basic Usage

[NOTE] The SDK is optimized to defer everything possible to a later time while making sure each module executes other code with a delay of some seconds. This ensures that applicationDidFinishLaunching: will process as fast as possible and the SDK will not block the startup sequence resulting in a possible kill by the watchdog process.

After you have set up the SDK as described above, the MSAITelemetryManager-instance is the central interface to track events, traces, metrics, page views or handled exceptions.

For an overview of how to use the API and view the results in the Application Insights resource, see API Overview. The examples are in Java, but the principles are the same.

6.1 Objective-C

// Send an event with custom properties and measurements data
[MSAITelemetryManager trackEventWithName:@"Hello World event!"
                              properties:@{@"Test property 1":@"Some value",
                                           @"Test property 2":@"Some other value"}
                            measurements:@{@"Test measurement 1":@(4.8),
                                           @"Test measurement 2":@(15.16),
                                           @"Test measurement 3":@(23.42)}];

// Send a message
[MSAITelemetryManager trackTraceWithMessage:@"Test message"];

// Manually send pageviews with a duration of 200 ms (note: this will also be done automatically)
[MSAITelemetryManager trackPageView:@"MyViewController"
                           duration:200
                         properties:@{@"Test measurement 1":@(4.8)}];

// Send custom metrics
[MSAITelemetryManager trackMetricWithName:@"Test metric" value:42.2];

6.2 Swift

// Send an event with custom properties and measuremnts data
MSAITelemetryManager.trackEventWithName("Hello World event!", 
                                  properties:["Test property 1":"Some value",
                                              "Test property 2":"Some other value"],
                                measurements:["Test measurement 1":4.8,
                                              "Test measurement 2":15.16,
                                              "Test measurement 3":23.42])

// Send a message
MSAITelemetryManager.trackTraceWithMessage("Test message")

// Manually send pageviews (duration 200 ms)
MSAITelemetryManager.trackPageView("MyViewController",
                                   duration:0.2,
                                 properties:["Test measurement 1":4.8])

// Send a message
MSAITelemetryManager.trackMetricWithName("Test metric", value:42.2)

View your data in the portal

In the Azure portal, open the application resource that you created to get your instrumentation key. You'll see charts showing counts of page views and sessions. To see more:

7. Advanced Usage

The SDK also allows for some more advanced usages.

7.1 Common Properties

It is also possible to set so-called "common properties" that will then be automatically attached to all telemetry data items.

Objective-C

[MSAITelemetryManager setCommonProperties:@{@"custom info":@"some value"}];

Swift

MSAITelemetryManager.setCommonProperties(["custom info":"some value"])

Filter your views by properties

Use the properties to segment and filter metric charts and filter searches.

8. Automatic collection of lifecycle events

Automatic collection of lifecycle events is enabled by default. This means that Application Insights automatically tracks the appearance of a view controller and manages sessions for you.

8.1. Page views

The automatic tracking of viewcontroller appearance can be disabled between setup and start of the SDK.

[MSAIApplicationInsights setup]; //setup the SDK
 
[[MSAIApplicationInsights sharedInstance] setAutoPageViewTrackingDisabled:YES]; //disable the auto collection

[MSAIApplicationInsights start]; //start using the SDK

8.2. Sessions

By default, the Application Insights for iOS SDK starts a new session when the containing app is restarted (this means a 'cold start', i.e. when the app has not already been in memory prior to being launched) or when it has been in the background for more than 20 seconds.

You can either change this timeframe:

[MSAIApplicationInsights setAppBackgroundTimeBeforeSessionExpires:60];

Turn of automatic session management completely:

[MSAIApplicationInsights setAutoSessionManagementDisabled:YES];

This then requires you to manage sessions manually:

[MSAIApplicationInsights renewSessionWithId:@"4815162342"];

8.3. Users

Normally, a random anonymous ID is automatically generated for every user of your app by the SDK. Alternatively you can set your own user ID or other user attributes, which will then be attached to all telemetry events:

  [[MSAIApplicationInsights sharedInstance] setUserWithConfigurationBlock:^(MSAIUser *user) {
    user.userId = @"your_user_id";
    user.accountId = @"[email protected]";
  }];

9. Set Custom Server Endpoint

You can also configure a different server endpoint for the SDK if needed using a full URL

[MSAIApplicationInsights setup]; //setup the SDK

[[MSAIApplicationInsights sharedInstance] setServerURL:@"https://YOURDOMAIN/path/subpath"];
  
[MSAIApplicationInsights start]; //start using the SDK

10. Documentation

Our documentation can be found on CocoaDocs.

11. Contributing

We're looking forward to your contributions via pull requests.

Development environment

  • Mac running the latest version of OS X
  • Get the latest Xcode from the Mac App Store
  • AppleDoc
  • Cocoapods

11.1 Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

11.2 Contributor License

You must sign a Contributor License Agreement before submitting your pull request. To complete the Contributor License Agreement (CLA), you will need to submit a request via the form and then electronically sign the CLA when you receive the email containing the link to the document. You need to sign the CLA only once to cover submission to any Microsoft OSS project.

12. Contact

If you have further questions or are running into trouble that cannot be resolved by any of the steps here, feel free to open a GitHub issue here or contact us at [email protected]

applicationinsights-ios's People

Contributors

ashtom avatar dtweston avatar hammyhavoc avatar lumaxis avatar matthiaswenz avatar paxos avatar readmecritic avatar southwood avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

applicationinsights-ios's Issues

Carthage Support

More and more I am seeing developers move to Carthage from Cocoapods due to it being a cleaner way of managing dependencies. Would it be possible to add support to this SDK?

Pod

Could this be made into a pod?

Rebuild with bit code enabled

Building with the latest Xcode 7.0 beta 6 (7A192o), I get the following error about the framework not being built with bit code.

I am including the framework via Cocoapods and am include 1.0-beta.6 of the App insights iOS framework.

ApplicationInsights/ApplicationInsights/ApplicationInsights.framework/ApplicationInsights(MSAIApplicationInsights.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The 1.0-beta.3 release zip doesn't match source code

This seems to be an odd problem. The 1.0-beta.3 release zip still has the MSAICrashMetaData.h file included within it, but that file is not imported in the ApplicationInsights.h umbrella header, so the module fails to compile in Xcode. If I add `#import "MSAICrashMetaData.h" to the umbrella header, everything seems to compile correctly.

However, when I look at the git repo, this file has been removed from the latest release. Is this a bad release binary?

Bitcode

When I tried compiling an app with the app insights SDK it said I need to disable bitcode, but bitcode is required to be on (for all targets, even the main app, I read) for a project that has a watch app :(

Improve error reporting and alerting

If you want to get alerted by Application Insights when an error occurs in an iOS app, you have to use the trackException method. This shows up in the portal as a "crash", but it manifests as the "Server exceptions" metric in the alert rules. The trackException method does not allow you to include a properties dictionary, so then you have to send an additional trackTraceWithMessage:properties: or trackEventWithName:properties: call to send additional property information (the TrackException method in the .NET API does allow you to send additional properties and metrics). This seems very unpolished, especially since the use of exceptions in iOS isn't standard.

Please have a look at crashDataHeadersId generation

Tracing with specific severity

There is an enum MSAISeverityLevel which defines severities but there are no samples showing its usage and a search through sources didn't bring more clarity. Is it in use? Can you show how it should be used with, for instance, trackTraceWithMessage?
I should be able to choose specific severity while sending messages to App Insights server. And I would expect to see messages created with severity Error or Critical in the Portal's section named Failures.
Are these valid asks?

Duplicate symbols when using with HockeyApp

Hello! I tried again to use App Insights (beta 7) with HockeyApp (preseason) and I'm getting some duplicate symbol errors when I build the project:

duplicate symbol _defaultFileCount in:
    /Users/jessicayeh/Documents/OmniBuzz/iOS and Apple Watch/Vendor/ApplicationInsights/ApplicationInsights.framework/ApplicationInsights(MSAIPersistence.o)
    /Users/jessicayeh/Documents/OmniBuzz/iOS and Apple Watch/Vendor/HockeySDK.embeddedframework/HockeySDK.framework/HockeySDK(BITPersistence.o)
duplicate symbol _kPersistenceQueueString in:
    /Users/jessicayeh/Documents/OmniBuzz/iOS and Apple Watch/Vendor/ApplicationInsights/ApplicationInsights.framework/ApplicationInsights(MSAIPersistence.o)
    /Users/jessicayeh/Documents/OmniBuzz/iOS and Apple Watch/Vendor/HockeySDK.embeddedframework/HockeySDK.framework/HockeySDK(BITPersistence.o)
duplicate symbol _kFileBaseString in:
    /Users/jessicayeh/Documents/OmniBuzz/iOS and Apple Watch/Vendor/ApplicationInsights/ApplicationInsights.framework/ApplicationInsights(MSAIPersistence.o)
    /Users/jessicayeh/Documents/OmniBuzz/iOS and Apple Watch/Vendor/HockeySDK.embeddedframework/HockeySDK.framework/HockeySDK(BITPersistence.o)
ld: 3 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I also cleaned the project and deleted derived data.

Generate test crash wiki out of date

On this wiki page:
https://github.com/Microsoft/ApplicationInsights-iOS/wiki/How-to-Generate-a-Test-Crash

The code snippet for triggering a crash is out of date. Instead of:

[[[MSAIApplicationInsights sharedInstance] crashManager] generateTestCrash];

It should be*

[[MSAICrashManager sharedManager] generateTestCrash];

* I haven't actually tested this in objc. I'm writing mine in Swift and this worked for me:

MSAICrashManager.sharedManager().generateTestCrash()

Handled exceptions are always sent as crashes and not as handled exceptions

I have this code:

@try {
    @throw [[NSException alloc] initWithName:@"test" reason:@"reason"];
} @catch (NSException *exception) {
    [MSAITelemetryManager trackException:exception];
}

This is tracked as a crash in the portal, but it's a handled exception.

Taking a look at the source code shows all exceptions go through the crash reporting process, regardless of handled or not. - https://github.com/Microsoft/ApplicationInsights-iOS/blob/master/Classes/MSAITelemetryManager.m#L239-L254

Until this is handled I guess the workaround would be to use traceMessage with custom properties?

No user id is sent for iOS

No user id is sent for iOS. This is manifesting itself as lack of user information in the portal (users = 0)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.