I am trying to create Bitcoin Payment in my IOS project. I'm using swift language. I search this topic in lots of sites, youtube, stack overflow. but i just getting HTTP request related topics. Any one have solution? Ping me...
3 Answers
Core Bitcoin is a library for iOS written in Objective-C. I have worked with it in Swift using the bridging header.
I myself have written a few Swift classes, in my experimental/educational wallet, for creating addresses, keys, and transactions, but I wouldn't recommend using it for anything. Feel free to take a look and see if you find anything interesting, or anything that you could learn from.
I suggest you to use BitPay's payment API, using Swift's URLRequest. See this answer and this answer for Swift documentation, and this webpage for BitPay API documentation.
Please note that if your app uses Bitcoin payment system your app may not be liked by Apple.
BitcoinKit is a Swift SDK proposing a Bitcoin wallet implementation. This is a full implementation of SPV node including wallet creation
, restore
, synchro with network
, sending
and receiving
transactions, etc. Also, look at BitcoinKit on CocoaPods.
Here's a code snippet showing how it looks like:
import UIKit
import BitcoinKit
class ViewController: UIViewController {
@IBOutlet private weak var qrCodeImageView: UIImageView!
@IBOutlet private weak var addressLabel: UILabel!
@IBOutlet private weak var balanceLabel: UILabel!
@IBOutlet private weak var destinationAddressTextField: UITextField!
private var wallet: Wallet? = Wallet()
override func viewDidLoad() {
super.viewDidLoad()
self.createWalletIfNeeded()
self.updateLabels()
}
func createWalletIfNeeded() {
if wallet == nil {
let privateKey = PrivateKey(network: .testnetBCH)
wallet = Wallet(privateKey: privateKey)
wallet?.save()
}
}
func updateLabels() {
qrCodeImageView.image = wallet?.address.qrImage()
addressLabel.text = wallet?.address.cashaddr
if let balance = wallet?.balance() {
balanceLabel.text = "Balance : \(balance) satoshi"
}
}
func updateBalance() {
wallet?.reloadBalance(completion: { [weak self] (utxos) in
DispatchQueue.main.async { self?.updateLabels() }
})
}
@IBAction func didTapReloadBalanceButton(_ sender: UIButton) {
updateBalance()
}
@IBAction func didTapSendButton(_ sender: UIButton) {
guard let addressString = destinationAddressTextField.text
else { return }
do {
let address: BitcoinAddress = try AddressFactory.create(addressString)
try wallet?.send(to: address, amount: 10000, completion: { [weak self] (response) in
print(response ?? "")
self?.updateBalance()
})
} catch {
print(error)
}
}
}