Last active
January 12, 2018 10:25
-
-
Save zcrowe/114b78c7152bcb8e0ff3f8b9f2784aaa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// AmigoHelper.swift | |
// | |
// Created by Zaid Crowe on 04/01/2018. | |
// Copyright © 2018 Team Extension. All rights reserved. | |
// | |
import Foundation | |
class AmigoHelper { | |
enum AmigoError: Error { | |
case CantCreateUpdateJSON | |
case GetDataEncodingWrong | |
} | |
static func loadAmigo (amigoWebView: UIWebView, apiKey: String) { | |
let checkAmigoExists = "typeof Amigo.load" | |
if let amigoExists = amigoWebView.stringByEvaluatingJavaScript(from: checkAmigoExists) { | |
if(amigoExists == "function"){ | |
amigoWebView.stringByEvaluatingJavaScript(from: "Amigo.load()") | |
} else { | |
amigoWebView.stringByEvaluatingJavaScript(from: "(function amigo(i,n,j,e,c,t){i.amigoConfig={apiKey:'"+apiKey+"'};c=n.createElement(j);c.async=1;c.src=e+'?api_key='+encodeURIComponent(i.amigoConfig.apiKey);t=n.getElementsByTagName(j)[0];t.parentNode.insertBefore(c,t)}(window,document,'script','https://private-dat.herokuapp.com/static/amigo-loader.js'));") | |
} | |
} | |
} | |
static func updateData (amigoData: Dictionary<String, Any>, amigoWebView: UIWebView, apiKey: String) throws { | |
let theJSONData = try JSONSerialization.data(withJSONObject: amigoData, options: .prettyPrinted) | |
guard let amigoDataJSONText = String(data: theJSONData, encoding: String.Encoding.ascii) else { | |
throw(AmigoError.CantCreateUpdateJSON) | |
} | |
amigoWebView.stringByEvaluatingJavaScript(from: "amigoData = \""+amigoDataJSONText+"\"") | |
loadAmigo(amigoWebView: amigoWebView, apiKey: apiKey) | |
} | |
static func getData (amigoWebView: UIWebView, apiKey: String) throws -> Dictionary<String, Any> { | |
loadAmigo(amigoWebView: amigoWebView, apiKey: apiKey) | |
let amigoDataString: String = amigoWebView.stringByEvaluatingJavaScript(from: "amigoData")! | |
guard let amigoData = amigoDataString.data(using: .utf8) else { | |
throw(AmigoError.GetDataEncodingWrong) | |
} | |
let amigoDict = try JSONSerialization.jsonObject(with: amigoData, options: []) as? [String: Any] | |
return amigoDict ?? [:] | |
} | |
} | |
squarefrog
commented
Jan 12, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment