Example of Working with Transactions

To work with transactions, create the HHFWTransactions application, which uses framework methods:

Method name Brief description
initWithCredentials (_: host: environment: project: device:) The method initializes the framework.
auth (_: password:) The method authenticates the user by login and password.
table (_: transactionID: tableCallParams: handler:) The method returns resource table data without loading to database.
retryTable (_: transactionID: tableCallParams: handler:) The method executes repeated requests to a mobile platform server to get saved data marked with transaction ID.
getAllTransactionResourceName (_: handler:) The method returns the list of all transactions.
getTransaction (_: resourceName: handler:) The method returns response from a mobile platform server by transaction ID.
deleteTransaction (_: resourceName: handler:) The method deletes transaction information.

Auxiliary methods:

Method name Brief description
getTransactionIDs (from:) The method returns the array of values for the uuid key from request's json result to get the list of all transactions.
Type of returned data: [String]
parseServerJSONResponse (json:) The method returns the result of converting the NSDictionary json dictionary to the [String: Any]? dictionary.
Type of returned data: [String: Any]?

The application can be used to get responses on repeated requests on disconnection using transaction ID and without addressing the data source.

NOTE. Use sending of transaction data if caching is not set up.

For details about transaction ID see the Sending Transaction Data section.

The HHFWTransactions application includes one screen, the UITextView text view, the UITextField txt box and UIButton buttons:

NOTE. When the application is initialized, authentication is executed, the buttons are not available. If the authentication is successful, the buttons are available, and the text box displays the text "Authentication success".

To execute the example:

  1. Click the Get All Transactions button.

Clicking the button initializes the request of the list of all recorded transactions. The application makes it easy to understand information by displaying the processed response from a mobile platform server as am array of transaction IDs.

  1. Click the Perform Request button.

Clicking the button executes the request without specifying transaction ID.

  1. Click the Get All Transactions button to check the list of all transactions. The list is not changed.

  1. Click the Perform Request with UUID button.

Clicking the button executes the request with specifying transaction ID generated randomly and displayed in the text box. The transactionId is added to request description.

  1. Click the Get All Transactions button to check the list of all transactions. The list displays the request with transaction ID.

  1. Click the Retry Request button.

Clicking the button sends repeated requests with the specified transaction ID to get the response that was not received by some reason, for example, on disconnection from a mobile platform server.

NOTE. Clicking the Get Transaction button returns the identical result.

  1. Enter the transaction ID to delete 8D8C0F5A-173D-4959-8C9C-2B82DA46982B into the text box.

  2. Click the Delete Transaction button.

Clicking the button deletes the specified transaction from the general transactions list.

  1. Click the Get All Transactions button to check if the transaction is deleted. The transactions list does not contain the transaction deleted before.

Application code:

import UIKit
 
class ViewController: UIViewController {
 
    // Determine output variables
    @IBOutlet weak var uuidTextField: UITextField!
    @IBOutlet weak var requestResultTextView: UITextView!
    @IBOutlet weak var requestButton: UIButton!
    @IBOutlet weak var requestWithUUIDButton: UIButton!
    @IBOutlet weak var retryRequestWithUUIDButton: UIButton!
    @IBOutlet weak var getAllTrtansactionButton: UIButton!
    @IBOutlet weak var getTransactionButton: UIButton!
    @IBOutlet weak var deleteTransactionButton: UIButton!
 
    // Redetermine method
    override func viewDidLoad() {
        super.viewDidLoad()
        self.deactivateButtons()
        self.initializeFramework()
        self.auth {
            self.activateButtons()
            self.requestResultTextView.text = "Authentication success"
        }
    }
 
    // Set method that will be executed on button click
     @IBAction func viewTapped(_ sender: UITapGestureRecognizer) {
        self.uuidTextField.resignFirstResponder()
    }
 
    @IBAction func requestPressed() {
        self.requestTable { (jsonResult) in
            self.requestResultTextView.text = String(format: "%@", jsonResult)
        }
    }
 
    @IBAction func requestWithUUIDPressed() {
        let uuid = UUID().uuidString
        self.uuidTextField.text = uuid
        self.requestTable(uuid) { (jsonResult) in
            self.requestResultTextView.text = String(format: "%@", jsonResult)
        }
    }
 
    @IBAction func retryPressed() {
        if let uuid = self.uuidTextField.text {
            self.retryRequest(transactionID: uuid) { (jsonResult) in
                self.requestResultTextView.text = String(format: "%@", jsonResult)
            }
        }
    }
 
    @IBAction func getAllTransactionsPressed(_ sender: UIButton) {
        self.getAllTransactions { (jsonResult) in
            self.requestResultTextView.text = String(format: "%@", self.getTransactionIDs(from: jsonResult))
        }
    }
 
    @IBAction func getTransactionPressed(_ sender: UIButton) {
        if let uuid = self.uuidTextField.text {
            self.getTransaction(transactionID: uuid) { (jsonResult) in
                self.requestResultTextView.text = String(format: "%@", jsonResult)
            }
        }
    }
 
    @IBAction func deleteTransactionPressed(_ sender: UIButton) {
        if let uuid = self.uuidTextField.text {
            self.deleteTransaction(transactionID: uuid) { (jsonResult) in
                self.requestResultTextView.text = String(format: "%@", jsonResult)
            }
        }
    }
 
    // Initialize framework
    private func initializeFramework() {
        let apiVersion: String = "v1"
        let host: String = "http://testmasterfmp.fsight.cloud/"
        let environment: String = "Leonid_environment"
        let project: String = "Leonid_project"
        let device: String = (UIDevice.current.identifierForVendor?.uuidString)!
        HHFWController.sharedInstance().initWithCredentials(
            apiVersion,
            host: host,
            environment: environment,
            project: project,
            device: device
        )
    }
 
    // Authenticate
    private func auth(completion: @escaping ()->()) {
        let username: String = "Leonid"
        let password: String = "123123"
        HHFWController.sharedInstance().auth(username, password: password){ (jsonResult) in
            if let jsonDict = jsonResult as? NSDictionary,
                let status = jsonDict["status"] as? String, status == "ok" {
                print("Auth success")
                completion()
            } else {
                print("Auth error")
            }
        }
    }
 
    // Perform the Table request
    private func requestTable(_ transactionID: String? = nil, completion: @escaping (NSDictionary)->()) {
        let resourceName = "GetBudgetPlanning"
        let tableCallParams = TableCallParams(defaultProperty: ())
        HHFWController.sharedInstance().table(resourceName, transactionID: transactionID, tableCallParams: tableCallParams) { (jsonResult) in
            if let jsonDict = jsonResult as? NSDictionary,
                let status = jsonDict["status"] as? String, status == "ok" {
                print("Table request success")
                completion(jsonDict)
            } else {
                print("Table request error")
            }
        }
    }
 
    // Perform the RetryTable request
    private func retryRequest(transactionID: String, completion: @escaping (NSDictionary)->()) {
        let resourceName = "GetBudgetPlanning"
        let tableCallParams = TableCallParams(defaultProperty: ())
        HHFWController.sharedInstance().retryTable(resourceName, transactionID: transactionID, tableCallParams: tableCallParams) { (jsonResult) in
            if let jsonDict = jsonResult as? NSDictionary,
                let status = jsonDict["status"] as? String, status == "ok" {
                print("Retry table request success")
                completion(jsonDict)
            } else {
                print("Retry table request error")
            }
        }
    }
 
    // Get transactions list
    private func getAllTransactions(completion: @escaping (NSDictionary)->()) {
        let resourceName = "GetBudgetPlanning"
        HHFWController.sharedInstance().getAllTransactionResourceName(resourceName) { (jsonResult) in
            if let jsonDict = jsonResult as? NSDictionary,
                let status = jsonDict["status"] as? String, status == "ok" {
                print("Get all transactions success")
                completion(jsonDict)
            } else {
                print("Get all transactions error")
            }
        }
    }
 
    // Get specific transaction
    private func getTransaction(transactionID: String, completion: @escaping (NSDictionary)->()) {
        let resourceName = "GetBudgetPlanning"
        HHFWController.sharedInstance().getTransaction(transactionID, resourceName: resourceName) { (jsonResult) in
            if let jsonDict = jsonResult as? NSDictionary,
                let status = jsonDict["status"] as? String, status == "ok" {
                print("Get transaction success")
                completion(jsonDict)
            } else {
                print("Get transaction error")
            }
        }
    }
 
    // Delete specific transaction
    private func deleteTransaction(transactionID: String, completion: @escaping (NSDictionary)->()) {
        let resourceName = "GetBudgetPlanning"
        HHFWController.sharedInstance().deleteTransaction(transactionID, resourceName: resourceName) { (jsonResult) in
            if let jsonDict = jsonResult as? NSDictionary,
                let status = jsonDict["status"] as? String, status == "ok" {
                print("Delete transaction success")
                completion(jsonDict)
            } else {
                print("Delete transaction error")
            }
        }
    }
 
    // Call auxiliary classes
    private func getTransactionIDs(from json: NSDictionary) -> [String] {
        var transactionIDs: [String] = []
        if let jsonDict = self.parseServerJSONResponse(json: json),
            let result = jsonDict["result"] as? [String: Any],
            let transactions = result["raw"] as? [[String: Any]] {
            for transaction in transactions {
                if let transactionID = transaction["uuid"] as? String {
                    transactionIDs.append(transactionID)
                }
            }
        }
        return transactionIDs
    }
 
    func parseServerJSONResponse(json: NSDictionary) -> [String: Any]? {
        return json as? [String: Any]
    }
 
    // Set methods to display application user interface elements
    private func deactivateButtons() {
        self.requestButton.isEnabled = false
        self.requestWithUUIDButton.isEnabled = false
        self.retryRequestWithUUIDButton.isEnabled = false
        self.getAllTrtansactionButton.isEnabled = false
        self.getTransactionButton.isEnabled = false
        self.deleteTransactionButton.isEnabled = false
    }
 
    private func activateButtons() {
        self.requestButton.isEnabled = true
        self.requestWithUUIDButton.isEnabled = true
        self.retryRequestWithUUIDButton.isEnabled = true
        self.getAllTrtansactionButton.isEnabled = true
        self.getTransactionButton.isEnabled = true
        self.deleteTransactionButton.isEnabled = true
    }
}

See also:

Examples of iOS Framework Use