Tutorials
No Results
Tutorial

Beginner · 30 minutes

Developing iOS apps Using Swift SDK

This tutorial teaches you the first steps in how to implement a transaction with the Algorand network on Xcode. The objective is first how to Install and use the Algorand Swift SDK Package on Xcode and then create an Ios application using SwiftUI and perform the transaction using the PureStake API and MyAlgo Wallet.

Requirements

Xcode 12 Developer Download Here
Swift Algorand-Sdk Download Here
PureStake Account Create
TestNet Account See Tutorial
My Algo Algorand Wallet Create

Background

Steps

1. Create SwiftUI Project

First let’s start to create your project.
Open Xcode, select File and on New choose “New project”.

EditorImages/2021/04/28 00:14/1firstIosWhite_jrVFncX.png

Let’s start with iOS App

EditorImages/2021/04/28 00:15/2firstiosWhite.png

2. Add Swift Algorand Sdk Packages

First “l like to thank Jesulonimi21 for the Swift Algorand-Sdk.” Go to the following link and copy the main Branch.
https://github.com/Jesulonimi21/Swift-Algorand-Sdk
EditorImages/2021/03/23 18:31/3Git.png

Second, add the Swift Algorand-Sdk Package Dependency. Select Branch - main and hit the next button, you’ve successfully added the packages.

EditorImages/2021/04/28 00:16/4packageWhite.png

EditorImages/2021/04/28 00:16/6packageWhite.png

3. PureStake API Configuration

PureStake can easily get up and running on the Algorand Network. To know more check this link https://developer.algorand.org/tutorials/getting-started-purestake-api-service/#1-create-a-purestake-api-account a walkthrough for using the PureStake API to interact with the Algorand network.

First, need to set the PureStake API address and past your API key on the Token. Please don’t share your API Key.

import SwiftUI
import swift_algorand_sdk

struct fuelService: View {
    var ALGOD_API_ADDR="https://testnet-algorand.api.purestake.io/ps2"
    var ALGOD_API_TOKEN=Gs——————————————————“
    var ALGOD_API_PORT=""

Second, need to set the client,

let algodClient=AlgodClient(host: ALGOD_API_ADDR, port: ALGOD_API_PORT, token: ALGOD_API_TOKEN)
  algodClient.set(key: "X-API-KeY")

4. Account Configuration

Now you need to create your Wallet and set your mnemonic. Never share your mnemonic secret key. For this tutorial, I use MyAlgo Wallet as my main wallet for the transaction. You can go to https://wallet.myalgo.com/access and create your account. Use Algorand dispenser to add founds to my wallet.
First your mnemonic account,

let mnemonic = "star star star star star star star star star star star star star star star star star star star star star star star star star”

Second your address Key,

let account = try Account(mnemonic)

 let senderAddress = account.getAddress()
 let receiverAddress = try! 
Address("KRRRRRRRRRRRRRRRRRRRRRRRRR")

5. SwiftUI Exploring user Interface

To keep things simple, just go over how the interface is organized. At the top you have the toolbar, that can let you toggle the navigator on the left and toggle the inspectors area on the right.
In the navigator, we can start to create your SwiftUI views and start to edit your code in the editor area and get the result on the canvas.

EditorImages/2021/04/28 00:17/7userWhite.png

6. SwiftUI Constructing the Views

For this project, I build three Views. Each view will be a Struct a view protocol, with a body property. This implementation allows swift to render the view on the screen.

The ContentView
This first View is where we can run the full App. The ContentView is the main stage where all the other views will be showed. Here I create three Stacks, one for the Menu Image, the other for Text and the last for the Service.

EditorImages/2021/04/28 00:17/9ContentViewWhite.png

The FuelService
This View is where the transaction is made and where we request the service.
Later in this view, I can populate with other services reusing this View and still using the transaction service.

EditorImages/2021/04/28 00:18/8_FuelService_White.png

The Transaction
This View is where you can see the transaction result. Here I create a simple Stack showing the result.

EditorImages/2021/04/28 00:18/10TransacWhite.png

7. SwiftUI and Algorand interaction

Here we request the service and add a call setting the amount and the destination address.

 Button(action: {
                    self.requestFuelService()
               }) {
                Image("buyBtnBlue")
                    .padding(.leading, 190.0)
                    .padding(.top, 80.0)

            }


            .fullScreenCover(isPresented: $transactionIsShowing, onDismiss: {}, content: {
                newApp.transaction(transactionIsShowing: $transactionIsShowing)
              })

8. Create a transaction

The transaction example it’s available on the Algorand Swift SDK .

  func  requestFuelService(){

        let algodClient=AlgodClient(host: ALGOD_API_ADDR, port: ALGOD_API_PORT, token: ALGOD_API_TOKEN)
        algodClient.set(key: "X-API-KeY")

        do {

            let mnemonic = "star star star star star star star star star star star star star star star star star star star star star star star star star"

            let account = try Account(mnemonic)
            //all fine with jsonData here

            let senderAddress = account.getAddress()
            let receiverAddress = try! Address("K--------------------------")




            algodClient.transactionParams().execute(){ paramResponse in
                if(!(paramResponse.isSuccessful)){
                    print(paramResponse.errorDescription!);
                    print("passou")
                    return;
                }


                let tx = try? Transaction.paymentTransactionBuilder().setSender(senderAddress)
                    .amount(1000000)
                    .receiver(receiverAddress)
                    .note("Swift Algo sdk is cool".bytes)
                    .suggestedParams(params: paramResponse.data!)
                    .build()


                let signedTransaction=account.signTransaction(tx: tx!)

                let encodedTrans:[Int8]=CustomEncoder.encodeToMsgPack(signedTransaction)



                algodClient.rawTransaction().rawtxn(rawtaxn: encodedTrans).execute(){
                    response in
                    if(response.isSuccessful){
                        print(response.data!.txId)
                        print("Sucesso")
//
                        transactionIsShowing = true
//
                    }else{
                        print(response.errorDescription!)
                        print("Failed")
                    }

                }
            }

        } catch {
            //handle error
            print(error)
        }
        print("algo buy!")
    }

9. Execute and Check

After push the request, we get the result of our buy in Algos.

if(response.isSuccessful){
                        print(response.data!.txId)

                        transactionIsShowing = true

EditorImages/2021/03/24 21:24/12front.png
EditorImages/2021/03/24 21:24/13req.png

10. Github Project

Go to the following link and try the full project.

https://github.com/3dlifee/algoandSwift.git

Thanks.

April 30, 2021