Bắt đầu với TheRPC
Tham khảo API
Ethereum API
Core API
Hướng dẫn

Swift Tools

Swift developers can use several libraries for Ethereum development, with web3.swift being the most popular choice for iOS and macOS applications.

Chú ý!
Xin chào! Lưu ý thân thiện: trang này nhằm cung cấp cho bạn tổng quan chi tiết về việc làm việc với Swift các yêu cầu. Đối với ví dụ mã thực tế, hãy xem API Methods documentation nơi bạn sẽ tìm thấy các ví dụ sẵn sàng sử dụng trong tất cả các ngôn ngữ được hỗ trợ!

# Web3.swift

Native Swift implementation for Ethereum.

import Web3
import BigInt

class EthereumClient {
    private let web3 = Web3(rpcURL: "YOUR_ETHEREUM_NODE_URL")

    func getBalance(address: String) async throws -> Double {
        let address = try EthereumAddress(hex: address, eip55: true)
        let balance = try await web3.eth.getBalance(address: address)
        return balance.converted(to: .ether).value
    }

    func sendTransaction(
        from: EthereumPrivateKey,
        to: String,
        amount: Double
    ) async throws -> String {
        let toAddress = try EthereumAddress(hex: to, eip55: true)
        let amount = EthereumAmount(value: amount, unit: .ether)

        let transaction = try await web3.eth.prepareTransaction(
            to: toAddress,
            value: amount,
            from: from.address
        )

        let signed = try transaction.sign(with: from)
        return try await web3.eth.send(transaction: signed)
    }
}
  • GitHub: web3.swift
  • Features:
    • Native Swift implementation
    • iOS and macOS support
    • Async/await support
    • Type-safe contract interactions
    • Wallet management
    • ENS support

# SwiftUI Integration

Modern SwiftUI example for Ethereum interactions:

import SwiftUI
import Web3

struct WalletView: View {
    @StateObject private var viewModel = WalletViewModel()

    var body: some View {
        VStack {
            Text("Balance: \(viewModel.balance) ETH")

            Button("Refresh") {
                Task {
                    await viewModel.updateBalance()
                }
            }
        }
    }
}

class WalletViewModel: ObservableObject {
    private let client = EthereumClient()
    @Published var balance: Double = 0

    func updateBalance() async {
        do {
            balance = try await client.getBalance(address: "YOUR_ADDRESS")
        } catch {
            print("Error: \(error)")
        }
    }
}

# Smart Contract Integration

Interact with smart contracts using Swift:

struct Contract {
    let web3 = Web3(rpcURL: "YOUR_ETHEREUM_NODE_URL")
    let contractAddress: EthereumAddress

    func callMethod() async throws -> String {
        let contract = try await web3.eth.Contract(
            json: contractABI,
            address: contractAddress
        )

        return try await contract.method(
            "methodName",
            parameters: [param1, param2],
            extraData: Data()
        ).call()
    }
}

# Error Handling

Proper Swift error handling for Ethereum operations:

enum EthereumError: Error {
    case invalidAddress
    case insufficientFunds
    case networkError(String)
}

extension EthereumClient {
    func safeGetBalance(address: String) async throws -> Double {
        guard address.hasPrefix("0x") else {
            throw EthereumError.invalidAddress
        }

        do {
            return try await getBalance(address: address)
        } catch {
            throw EthereumError.networkError(error.localizedDescription)
        }
    }
}

See also

Giúp chúng tôi trở nên tốt hơn!
Chia sẻ trang này và giúp chúng tôi tạo ra sản phẩm tốt hơn cho bạn.