Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

swift3 conversion #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 18 additions & 21 deletions GATracker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,9 @@ class GATracker {

//Set up singleton object for the tracker
class func setup(tid: String) -> GATracker {
struct Static {
static var onceToken: dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {
let _: () = {
_analyticsTracker = GATracker(tid: tid)
}
}()
return _analyticsTracker
}

Expand All @@ -58,22 +55,22 @@ class GATracker {
#endif

self.tid = tid
self.appName = NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
let nsObject: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
self.appName = Bundle.main.infoDictionary!["CFBundleName"] as! String

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should handle this conditional properly.

let nsObject: AnyObject? = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as AnyObject?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same thing here.
let nsObject: AnyObject? = Bundle.main.infoDictionary["CFBundleShorVersionString"] as? AnyObject should do the job.

self.appVersion = nsObject as! String
self.ua = "Mozilla/5.0 (Apple TV; CPU iPhone OS 9_0 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13T534YI"
self.MPVersion = "1"
let defaults = NSUserDefaults.standardUserDefaults()
if let cid = defaults.stringForKey("cid") {
let defaults = UserDefaults.standard
if let cid = defaults.string(forKey: "cid") {
self.cid = cid
}
else {
self.cid = NSUUID().UUIDString
defaults.setObject(self.cid, forKey: "cid")
self.cid = NSUUID().uuidString
defaults.set(self.cid, forKey: "cid")
}

let language = NSLocale.preferredLanguages().first
if language?.characters.count > 0 {
let language = NSLocale.preferredLanguages.first
if (language?.characters.count)! > 0 {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe if (language?.characters.count ?? 0) > 0 ?

self.ul = language!
} else {
self.ul = "(not set)"
Expand All @@ -93,16 +90,16 @@ class GATracker {
}

//Encoding all the parameters
if let paramEndcode = parameters.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet()){
if let paramEndcode = parameters.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed){
let urlString = endpoint + paramEndcode;
let url = NSURL(string: urlString);
let url = URL(string: urlString);

#if DEBUG
print(urlString)
#endif

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
if let httpReponse = response as? NSHTTPURLResponse {
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) -> Void in
if let httpReponse = response as? HTTPURLResponse {
let statusCode = httpReponse.statusCode
#if DEBUG
print(statusCode)
Expand All @@ -111,7 +108,7 @@ class GATracker {
else {
if (error != nil) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optionals should not be handled like this. Use if let error = error or some other optional binding mechanism.

#if DEBUG
print(error!.description)
print(error!.localizedDescription)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Proper handling will help you get rid of this forced-unwrapping usage.

#endif
}
}
Expand All @@ -130,7 +127,7 @@ class GATracker {
params.updateValue(value, forKey: key)
}
}
self.send("screenview", params: params)
self.send(type: "screenview", params: params)
}

func event(category: String, action: String, label: String?, customParameters: Dictionary<String, String>?) {
Expand All @@ -145,7 +142,7 @@ class GATracker {
params.updateValue(value, forKey: key)
}
}
self.send("event", params: params)
self.send(type: "event", params: params)
}

func exception(description: String, isFatal:Bool, customParameters: Dictionary<String, String>?) {
Expand All @@ -163,7 +160,7 @@ class GATracker {
params.updateValue(value, forKey: key)
}
}
self.send("exception", params: params)
self.send(type: "exception", params: params)

}
}
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ All code for this tracker is located inside a single file “GATracker.swift”.

This library creates an object (a tracker) that holds persistent values such as client id, property id, and more. The tracker is created with the following command:
```
GATracker.setup("UA-1234567-89")
GATracker.setup(tid: "UA-1234567-89")
```
This code should run in the AppDelegate method applicationDidFinishLaunchingWithOptions.

Expand All @@ -17,24 +17,24 @@ Once the tracker is set up you can start sending Google Analytics hits from your
### Screenview
When sending the screenview hit type, the screenname parameter is a required field.
```
GATracker.sharedInstance.screenView("FirstScreen", customParameters: nil)
GATracker.sharedInstance.screenView(screenName: "FirstScreen", customParameters: nil)
```
### Event
When sending the event hit type, the event category and action a required fields
```
GATracker.sharedInstance.event("category", action: "action", label: nil, customParameters: nil)
GATracker.sharedInstance.event(category: "category", action: "action", label: nil, customParameters: nil)
```
### Exception
When sending the exception hit, the exception description and exception “fatality” are both required parameters
```
GATracker.sharedInstance.exception("This test failed", isFatal: true, customParameters: nil)
GATracker.sharedInstance.exception(description: "This test failed", isFatal: true, customParameters: nil)
```
### Sending Additional Parameters
With each hit you are also able to send additional parameters as specified in the Measurement Protocol reference. Examples include: “non interactive hit”, “event value”, “custom dimensions”, “custom metrics” etc.

In the following example we will add custom metric values and set this event hit as non interactive. The example shows how to send a video progress hit that includes video name as custom dimension 1, video author as custom dimension 2 and sets the event as non interactive (since this event is not a result of user interaction).
```
GATracker.sharedInstance.event("Video", action: "Progress", label:"50%", customParameters: ["cd1":"Incredible Video", "cd2":"Amazing A. Uthor", "ni":1])
GATracker.sharedInstance.event(category: "Video", action: "Progress", label:"50%", customParameters: ["cd1":"Incredible Video", "cd2":"Amazing A. Uthor", "ni":1])
```
As mentioned before you are able to use any measurement protocol parameters inside the customParameters dictionary.
https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters?hl=en
Expand All @@ -44,12 +44,12 @@ Screenview, event and exception are not the only hit types available in Google A

In the following example we will send a transaction hit with transaction id 10001 and transaction revenue of $425,00.
```
GATracker.sharedInstance.send("transaction", params: ["tid":"10001", "tr":"425,00", "cu":"USD"])
GATracker.sharedInstance.send(type: "transaction", params: ["tid":"10001", "tr":"425,00", "cu":"USD"])
```

For additional information email [email protected] or visit our website http://www.analyticspros.com
### Sample App
When running the sample app make sure ot update the property id in the app delegate.
When running the sample app make sure to update the property id in the app delegate.
```
GATracker.setup("[insert your GA property id]")
GATracker.setup(tid: "[insert your GA property id]")
```