iOS SDK
You can use Nearpay Connect in your IOS app
- 1.
2. Import the framework into your projects
Steps:
- In the project navigator, select your project.
- Select your target.
- Select the "General" tab.
- Open "Framework , Libraries and Embedded Content" expander.
- Click the + button.
- Add file
- (optional) or you can just drag and drop the file to "Framework , Libraries and Embedded Content".


3. Add bluetooth as "Bluetooth Always Usage Description" to your info.

4. import NearpayConnectKit
import NearpayConnectKit
5. Define connectivity object
@StateObject var conn: Connectivity = Connectivity.shared
6. add this modifier in the end of root view
.nearpayConnectivity()
7. Add sessionDelegate in main root
.onAppear {
conn.sessionDelegate = self
}
8. Start Purchase
conn.startPurchaseTransaction(amount: 300)
9. Add extension to root view
extension ContentView: TransactionSessionDelegate
{
func transactionSesison(didReciviedDataFor transaction: NearpayConnectKit.RemoteTransaction?, withError error: Error?) {
print("data received \(transaction)")
}
func transactionSession(didEndWithFor transaction: NearpayConnectKit.RemoteTransaction?, withError error: Error?) {
print("data error \(error)")
}
}
This function is used to show the setupUI of Nearpay connect
conn.setupUI()

Purchase is used to send the amount to the other Device
conn.startPurchaseTransaction(amount: 300)
Reset setting is used to reset all the settings .
conn.resetSetting()
ShowUI is a Boolean to check if UI is opened or closed.
var uiStatus = conn.showUI // it will be true or false
Please check the example
SwiftUI
UIkit
Without NearpayConnect UI
import SwiftUI
import NearpayConnectKit
struct ContentView: View {
@StateObject var connecetivity : Connectivity = .shared
var body: some View {
VStack(spacing: 30) {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
.onTapGesture {
connecetivity.startPurchaseTransaction(amount: 300)
}
Button("settings")
{
connecetivity.setupUI()
}
Text("Hello, world! \(Connectivity.name)")
}
.padding()
.nearpayConnectivity()
.onAppear
{
connecetivity.sessionDelegate = self
}
}
}
extension ContentView: TransactionSessionDelegate
{
public func transactionSesison(didReciviedDataFor transaction: NearpayConnectKit.RemoteTransaction?, withError error: Error?) {
print("data received: \(transaction)")
}
public func transactionSession(didEndWithFor transaction: NearpayConnectKit.RemoteTransaction?, withError error: Error?) {
print("error received: \(transaction)")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import UIKit
import NearpayConnectKit
class ViewController: UIViewController {
@IBOutlet weak var btnClickable: UIButton!
var connectivity: Connectivity = Connectivity.shared
override func viewDidLoad() {
super.viewDidLoad()
connectivity.sessionDelegate = self
connectivity.hostingUIViewController = self
}
@IBAction func onTap(_ sender: Any) {
connectivity.setupUI()
btnClickable.titleLabel?.text = " ali "
}
@IBAction func btnStartTransaction(_ sender: Any) {
connectivity.startPurchaseTransaction(amount: 3922)
}
}
extension ViewController: TransactionSessionDelegate {
func transactionSesison(didReciviedDataFor transaction: NearpayConnectKit.RemoteTransaction?, withError error: Error?) {
print("data recived \(transaction)")
}
func transactionSession(didEndWithFor transaction: NearpayConnectKit.RemoteTransaction?, withError error: Error?) {
print("err recived \(error)")
}
}
import UIKit
import Combine
import NearpayConnectCore
struct LogData {
let text: String
let links: [String: String]
}
class ViewController: UIViewController {
@IBOutlet weak var reversalButton: UIButton!
@IBOutlet weak var refundButton: UIButton!
@IBOutlet weak var pairingLable: UILabel!
@IBOutlet weak var btnWebsocketConnect: UIButton!
@IBOutlet weak var forgetButton: UIButton!
@IBOutlet weak var lastPurchaseUUID: UILabel!
@IBOutlet weak var logsTable: UITableView!
var logs: [LogData] = []
var cancelable: AnyCancellable?
var lastTransactionUUID: String? = nil
{
didSet
{
reversalButton.isEnabled = lastTransactionUUID != nil
refundButton.isEnabled = lastTransactionUUID != nil
lastPurchaseUUID.text = lastTransactionUUID != nil ? "Last Purchase: \(lastTransactionUUID!)" : "No Approved purchase yet"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
Connectivity.shared.connectDelegate = self
Connectivity.shared.sessionDelegate = self
Connectivity.shared.bluetoothScanDelegate = self
logsTable.delegate = self
logsTable.dataSource = self
logsTable.rowHeight = UITableView.automaticDimension
logsTable.estimatedRowHeight = UITableView.automaticDimension
log(text: "Welcome ...")
cancelable = Connectivity.shared.$setting.sink(receiveValue: {
newValue in
if newValue.paired == .Local {
self.log(text: "paird to \(newValue.tcp.addressInfo[.host]!):\(newValue.tcp.addressInfo[.port]!)")
self.log(text: "pairing uuid \(newValue.tcp.addressInfo[.uuid] ?? "")")
self.pairingLable.text = "Paired.. \(newValue.tcp.connected ? "" : "Not") Connected"
self.forgetButton.isEnabled = true
}
if newValue.paired == .None {
self.log(text: "no paired device")
self.pairingLable.text = "Not paired"
self.forgetButton.isEnabled = false
}
})
Connectivity.shared.connectLastPairedDevice()
}
@IBAction func forgetPairedActoin(_ sender: Any) {
Connectivity.shared.forgetPaired()
}
@IBAction func btnConnectAction(_ sender: Any) {
if (sender as? UIButton)?.value(forKeyPath: "buttonType") as? Int == 1
{
if Connectivity.shared.connected
{
Connectivity.shared.disconectLocal()
}
else
{
Connectivity.shared.connectLocal(host: "192.168.102.141", port: 8080)
log(text: "Connecting tcp \(Connectivity.shared.setting.tcp.addressInfo[.host]!) ...")
}
}
if (sender as? UIButton)?.value(forKeyPath: "buttonType") as? Int == 0
{
log(text: "Scanning Bluetooth ...")
Connectivity.shared.scanBluetoothDevices()
}
}
@IBAction func btnActionStartTransaction(_ sender: Any) {
log(text: "Start Purchase Job")
Connectivity.shared.startPurchaseJob(amount: 434)
}
@IBAction func btnRefundTransaction(_ sender: Any) {
if let lastTransactionUUID
{
Connectivity.shared.startRefundJob(amount: 434, transactionUUID: lastTransactionUUID, adminPin: "0000")
}
}
@IBAction func btnReversalAction(_ sender: Any) {
if let lastTransactionUUID
{
Connectivity.shared.startReversalJob(transactionUUID: lastTransactionUUID)
}
}
@IBAction func btnReconcileJob(_ sender: Any) {
Connectivity.shared.startReconcileJob(adminPin: "0000")
}
func log(text: String)
{
log(text: text, links: [:])
}
func log(text: String, links: [String: String])
{
logs.insert(LogData(text: "#\(logs.count + 1 )\t: \(text)", links: links), at: 0)
logsTable.reloadData()
}
}
extension ViewController: ConnectivityConnectDelegate {
func connectivityConnect(didConnectFor: NearpayConnectCore.ConnectivitySetting) {
log(text: "Connected")
btnWebsocketConnect.titleLabel?.text = "Dissconnect"
}
func connectivityConnect(didCloseFor: NearpayConnectCore.ConnectivitySetting, withError error: Error?) {
log(text: "Closed \(error != nil ? error.debugDescription : "")")
btnWebsocketConnect.titleLabel?.text = "Connect WebSocket"
}
func connectivityConnect(didFailFor: NearpayConnectCore.ConnectivitySetting, withError error: Error?) {
log(text: "Failed \(error.debugDescription)")
btnWebsocketConnect.titleLabel?.text = "Coonect WebSocket"
}
}
extension ViewController: BluetoothScanDelegate
{
func bluetoothScan(didStopFor serviceId: String) {
log(text: "Bluetooth Scanning stoped ...")
}
func bluetoothScan(didStartFor serviceId: String) {
log(text: "Bluetooth Scanning started ...")
}
func bluetoothScan(didFoundDeviceFor serviceId: String, device: BluetoothDevice) {
log(text: "device founded \(device.name)")
Connectivity.shared.connectBluetoothDevice(device: device)
}
func bluetoothScan(didRefreshListFor serviceId: String, list: [BluetoothDevice]) {
}
}
extension ViewController: SessoinJobDelegate
{
func sessionJob(didReeceiveResultForPurchase result: JobResult<PurchaseResult, PurchaseError>) {
print("didReeceiveResultForPurchase")
log(text: "didReeceiveResultForPurchase")
switch result {
case .result(let outcome):
if case .APPROVED(let receipts) = outcome {
log(text: "APPROVED transactionID=\(receipts[0].transaction_uuid ?? "not found") receipt ", links: ["receipt": receipts[0].qr_code!])
if !receipts.isEmpty
{
lastTransactionUUID = receipts[0].transaction_uuid
}
}
if case .DECLIEND(let receipts) = outcome
{
if receipts.count > 0
{
log(text: "DECLIEND transactionID=\(receipts[0].transaction_uuid ?? "not found") receipt ", links: ["receipt": receipts[0].qr_code!])
}
else
{
log(text: "DECLIEND no receipts")
}
lastTransactionUUID = nil
}
case .failure(let error):
log(text: error.message())
lastTransactionUUID = nil
@unknown default:
log(text: "unkown result")
lastTransactionUUID = nil
}
}
func sessionJob(didReeceiveResultForRefund result: JobResult<RefundResult, RefundError>) {
log(text: "didReeceiveResultForRefund")
switch result {
case .result(let outcome):
if case .APPROVED(let receipts) = outcome {
log(text: "APPROVED transactionID=\(receipts[0].transaction_uuid ?? "not found") receipt ", links: ["receipt": receipts[0].qr_code!])
}
if case .DECLIEND(let receipts) = outcome {
if receipts.count > 0
{
log(text: "DECLIEND transactionID=\(receipts[0].transaction_uuid ?? "not found") receipt ", links: ["receipt": receipts[0].qr_code!])
}
else
{
log(text: "DECLIEND no receipts")
}
}
case .failure(let error):
log(text: error.message())
@unknown default:
log(text: "unknown result")
}
}
func sessionJob(didReeceiveResultForReversal result: JobResult<ReversalFinished, ReversalError>) {
log(text: "didReeceiveResultForReversal")
switch result {
case .result(let payload):
log(text: "Finished transactionID=\(payload.receipts[0].transaction_uuid ?? "not found") receipt ", links: ["receipt": payload.receipts[0].qr_code!])
case .failure(let error):
log(text: error.message())
@unknown default:
log(text: "unknown result")
}
}
func sessionJob(didReeceiveResultForReconciliation result: JobResult<ReconciliationResult, ReconciliationError>) {
log(text: "didReeceiveResultForReconciliation")
switch result {
case .result(let outcome):
if case .BALANCED(let receipt) = outcome {
log(text: "BALANCED receipt ", links: ["receipt": receipt.qr_code])
}
if case .NOT_BALANCED(let receipt) = outcome {
log(text: "NOT_BALANCED receipt ", links: ["receipt": receipt.qr_code])
}
case .failure(let error):
log(text: error.message())
@unknown default:
log(text: "unknown result")
}
}
}
extension ViewController: UITableViewDelegate
{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
extension ViewController: UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
logs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "logcell") as? LogCell
{
if indexPath.row == 0
{
cell.setLog(_text: logs[indexPath.row].text, top: true,links: logs[indexPath.row].links)
}
else
{
cell.setLog(_text: logs[indexPath.row].text, top: false,links: logs[indexPath.row].links)
}
return cell
}
return UITableViewCell()
}
}
Last modified 6mo ago