Skip to content

Tutorials 

Integrate mimik client library, edgeEngine on iOS - Swift

Prerequisites

1. Use the latest release version of Xcode (not a beta). [Xcode releases](https://xcodereleases.com)

2. Check that you have cocoapods installed on your Mac. [Cocoapods getting started](https://guides.cocoapods.org/using/getting-started.html)

3. Create a new example Xcode project or open an existing one.

4. Attach an iOS device to your Mac as simulators are not supported.

Integrate using cocoapods

If you just created a new Xcode project, run the following command in the root of the project directory (you don’t need to run this if your existing project already established the cocoapods distribution)


pod init

Then for both new or an existing project run


pod install

Now it’s time to add the mimik client library cocoapod to the Podfile configuration file.


platform :ios, '13.6'
source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/mimikgit/cocoapod-edge-specs.git'

target 'example' do
  use_frameworks!
  pod 'MIMIKEdgeMobileClient'
end

Then for both a new or an existing project run again


pod install

You should see the mimik client library and its dependencies being added to your project


Analyzing dependencies Downloading dependencies Installing MIMIKEdgeMobileClient Installing Alamofire Installing AppAuth Installing JWTDecode Installing KeychainSwift Installing SwiftyJSON

When this is done you should open your project’s .xcworkspace file in Xcode. Not the .xcodeproj file.

Initialize

You can initialize the mimik client library different ways, for example as an lazy variable in your controller:


import MIMIKEdgeMobileClient
lazy var mimikClientLibrary: MIMIKEdgeMobileClient = {
        let library = MIMIKEdgeMobileClient.init(license: nil)        
        guard let checkedLibrary = library else {
            fatalError()
        } 
        return checkedLibrary
    }()

Or as an immutable variable in a shared instance of a class


import MIMIKEdgeMobileClient

class MIMIKClient: NSObject {
    
    class var sharedInstance: MIMIKClient {
        struct Singleton {
            static let instance = MIMIKClient()
        }

        return Singleton.instance
    }
    
    var library: MIMIKEdgeMobileClient!
}

In any case you have to keep a strong reference to the mimik client library.

Configure

Optionally set client library log levels:

self.mimikClientLibrary.setClientLibraryLogLevel(to: .info)

Optionally set edgeEngine startup parameters:

let startupParameters = MIMIKStartupParameters.init(logLevel: .info, nodeInfoLevel: .on, nodeName: "custome node name")
self.mimikClientLibrary.setEdgeEngineStartupParameters(parameters: startupParameters)

Optionally set a custom edgeEngine port number, if you don’t want the client library to manage it for you.

guard self.mimikClientLibrary.setCustomPortNumber(number: 9000) else  {
    return
}

Control

Certain APIs, such as microservice deployment require the edgeEngine platform to be running. You can make this happing as following:

self.mimikClientLibrary.startEdgeEngine { result in
    guard result == true else {
        return
    }
    
    print("edgeEngine started")
} 

You can shut down the edgeEngine platform as following:

Please note that this is a synchronous, main thread blocking API call.

self.mimikClientLibrary.stopEdgeEngineSynchronously()
print("edgeEngine stopped")

Background

Client library will manage the edgeEngine state automatically for your project. If edgeEngine was running when the application was taken to the background, it will be started again automatically as soon as the application is taken back to the foreground. If edgeEngine was not running at that time, it will be not be started automatically.

Authorize

In order to use most mimik client library APIs you will need to authorize it using your developer id token that you can get in a three quick steps at the mimik developer portal. 

[Go to console, create account, create project, copy developer id token](

https://developer.mimik.com/console)

After you get your developer id token you can use it to authorize the mimik client library instance with the following:


let developerIdToken = "Place your developer id token from mimik developer portal console here"

self.mimikClientLibrary.authorizeWithDeveloperIdToken(developerIdToken: developerIdToken, completion: { result in
    
    guard result.error == nil, let checkedAccessToken = result.tokens?.accessToken, let checkedAccessTokenExpirationDate = result.tokens?.accessTokenExpirationDate else {
        return
    }
    
    print(#function, "\naccess token: ", checkedAccessToken, "\nexpires on: ", checkedAccessTokenExpirationDate)
    })

Keep the access token you get from the authorization call around, you will need it later for making further API calls to the mimik client library.

edgeEngine Information

The edgeEngine runtime information is also available.

let edgeEngineServiceLink = self.mimikClientLibrary.edgeEngineServiceLink()
let edgeEngineWorkingDirectory = self.mimikClientLibrary.edgeEngineWorkingDirectory()
let edgeEngineWebSocketServiceLink = self.mimikClientLibrary.edgeEngineWebSocketServiceLink()

Microservice deployment

The following deploys (installs) an edge microservice on the edgeEngine instance running on your device.

let accessToken = "place your access token from the authorizeWithDeveloperIdToken call here"
let microserviceName = "this needs to match your js microservice image name"
let config = MIMIKMicroserviceDeploymentConfig.init(imageName: microserviceName, containerName: microserviceName, baseApiPath: "/\(microserviceName)/v1", envVariables: ["key" : "value"])
let imageTarPath = "/bundle/microservice.tar" // path to the microservice.tar in the application bundle

self.mimikClientLibrary.deployMicroservice(edgeEngineAccessToken: accessToken, config: config, imageTarPath: imageTarPath) { microservice in
    
    guard let checkedMicroservice = microservice else {
        return
    }
    
    print("deployed microservice: ", checkedMicroservice.container?.description ?? "N/A", checkedMicroservice.image?.description ?? "N/A")
}
The following undeploys (uninstalls) an edge microservice from the edgeEngine instance on the device.
let accessToken = "place your access token from the authorizeWithDeveloperIdToken call here"
let microserviceName = "this needs to match your js microservice image name"
let config = MIMIKMicroserviceUndeploymentConfig.init(imageName: microserviceName, containerName: microserviceName)
self.mimikClientLibrary.undeployMicroservice(edgeEngineAccessToken: accessToken, config: config) { result in
    
    guard result == true else {
        fatalError()
    }
    
    print("microservice undeploy success")
}

Microservice information

You can get objects representing the deployed microservices.
let accessToken = "place your access token from the authorizeWithDeveloperIdToken call here"

self.mimikClientLibrary.deployedMicroservices(edgeEngineAccessToken: accessToken) { microservices in
    guard let checkedMicroservices = microservices else {
        return
    }
    
    for (_, microservice) in checkedMicroservices.enumerated() {
        
        guard let checkedImage = microservice.image, let checkedContainer = microservice.container else {
            continue
        }
        
        print("deployed microservice:", checkedImage.description, checkedContainer.description)
    }
}

Microservice call

Depending on how you’ve developed and packaged your js microservice this will vary slightly, but generally you can do the following in order to make an API call to your microservice deployed to the edgeEngine instance running on your device.
import Alamofire
let deployedMicroservice: MIMIKMicroservice?

guard let checkedBaseAPIPath = self.deployedMicroservice?.baseAPIPath() else {
    continue
}

let edgeEngineServiceLink = self.mimikClientLibrary.edgeEngineServiceLink()
let ownerCode = "place the same owner code you've used when deploying the microservice here" // example only
let queries = "?ownerCode=\(ownerCode)&types=self" // example only
let endpointWithQueries = "info" + queries // example only
let microserviceEndpointPath = edgeEngineServiceLink + checkedBaseAPIPath + "/" + endpointWithQueries
// all above values need to match your js microservice endpoint and models.

guard let url = URL.init(string: microserviceEndpointPath) else {
    return
}

let headers = ["Authorization" : "Bearer \(accessToken)"]
let httpHeaders = HTTPHeaders.init(headers)

AF.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: httpHeaders).responseJSON { response in
    
    guard let checkedDataJson = MIMIKEdgeMobileClient.validateMicroserviceResponse(response: response, encapsulatedData: false).dataJSON else {
        return
    }

    print(checkedDataJson)
}

Client Library Releases

You can check for the latest mimik client library releases at

[GitHub](https://github.com/mimikgit/cocoapod-MIMIKEdgeMobileClient/releases)

Support

You can get additional support at

[mimik developer portal](https://developer.mimik.com)

[StackOverflow](https://stackoverflow.com/questions/tagged/edgeengine)

Partners information

There is more information, examples and drop-in code available for mimik partners. Please contact us for more information at

[mimik.com](https://mimik.com/mimikcontact/)

Document Revision History

2021-07-13 Document created.

2021-07-15 Moved Authorization section down. Renamed three sections. Client Library Releases section updated.

Need more help?

Feel free to contact us on Stack Overflow or send us a question via our support page if you have any questions.

Your feedback is important to us ~