Swift 4 带有 UIPickerView 和获取请求修复程序的货币转换器 API

Swift 4 Currency Converter with UIPickerView and Get request Fixer API

我正在尝试构建一个货币转换器,使用 Swift 4。 我的主要问题仍然是我的应用程序在点击转换按钮时崩溃。我已经被这个问题困扰了 1 周了,我有点绝望。我在网上没有找到任何相关的解决方案,我仍然不明白我的错误在哪里,这真的很烦人。

我收到此错误消息:

Thread 1: signal SIGABRT

来自这行代码:

class AppDelegate: UIResponder, UIApplicationDelegate {

这是完整的消息:

2018-08-31 10:43:19.483566+0200 Baluchon[21101:1535106] -[Baluchon.CurrencyChangeViewController convert:]: unrecognized selector sent to instance 0x7fc51ef06680
2018-08-31 10:43:19.491934+0200 Baluchon[21101:1535106] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Baluchon.CurrencyChangeViewController convert:]: unrecognized selector sent to instance 0x7fc51ef06680'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010cfa71e6 __exceptionPreprocess + 294
    1   libobjc.A.dylib                     0x0000000109560031 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010d028784 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   UIKit                               0x000000010a0226db -[UIResponder doesNotRecognizeSelector:] + 295
    4   CoreFoundation                      0x000000010cf29898 ___forwarding___ + 1432
    5   CoreFoundation                      0x000000010cf29278 _CF_forwarding_prep_0 + 120
    6   UIKit                               0x0000000109df53e8 -[UIApplication sendAction:to:from:forEvent:] + 83
    7   UIKit                               0x0000000109f707a4 -[UIControl sendAction:to:forEvent:] + 67
    8   UIKit                               0x0000000109f70ac1 -[UIControl _sendActionsForEvents:withEvent:] + 450
    9   UIKit                               0x0000000109f6fa09 -[UIControl touchesEnded:withEvent:] + 580
    10  UIKit                               0x0000000109e6a0bf -[UIWindow _sendTouchesForEvent:] + 2729
    11  UIKit                               0x0000000109e6b7c1 -[UIWindow sendEvent:] + 4086
    12  UIKit                               0x0000000109e0f310 -[UIApplication sendEvent:] + 352
    13  UIKit                               0x000000010a7506af __dispatchPreprocessedEventFromEventQueue + 2796
    14  UIKit                               0x000000010a7532c4 __handleEventQueueInternal + 5949
    15  CoreFoundation                      0x000000010cf49bb1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    16  CoreFoundation                      0x000000010cf2e4af __CFRunLoopDoSources0 + 271
    17  CoreFoundation                      0x000000010cf2da6f __CFRunLoopRun + 1263
    18  CoreFoundation                      0x000000010cf2d30b CFRunLoopRunSpecific + 635
    19  GraphicsServices                    0x000000010f7daa73 GSEventRunModal + 62
    20  UIKit                               0x0000000109df4057 UIApplicationMain + 159
    21  Baluchon                            0x000000010890e0f7 main + 55
    22  libdyld.dylib                       0x000000010e0c3955 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

我正在遵循 MVC 模式,所以这是我的模型:

struct Currency: Decodable {
    let rates: [String: Double]?
}

class CurrencyChangeService {
    var currencies = [String]()
    var rate = [Double]()

    static var shared = CurrencyChangeService()
    private init() {}

    private static let currencyChangeUrl = URL(string: "http://data.fixer.io/api/latest?access_key=mykey")!
    var task: URLSessionDataTask?
    private var currencySession = URLSession(configuration: .default)

    init(currencySession: URLSession) {
        self.currencySession = currencySession
    }

    func getCurrencyChange(callback: @escaping (Bool, Currency?) -> Void) {
        task?.cancel()
        task = currencySession.dataTask(with: CurrencyChangeService.currencyChangeUrl) { data, response, error in
            DispatchQueue.main.async {
                guard let data = data, error == nil else {
                    callback(false, nil)
                    return
                }
                guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
                    callback(false, nil)
                    return
                }
                guard let responseJSON = try? JSONDecoder().decode(Currency.self, from: data) else {
                    callback(false, nil)
                    return
                }
                for (key, value) in responseJSON.rates! {
                    self.currencies.append(key)
                    self.rate.append(value)
                }
                callback(true, responseJSON)
            }
        }
        task?.resume()
    }
}

这是我的控制器:

import UIKit

class CurrencyChangeViewController: UIViewController {
    //MARK: - Outlets
    @IBOutlet weak var myValueTextField: UITextField!
    @IBOutlet weak var myCurrencyTextField: UITextField!
    @IBOutlet weak var myConvertedValueLabel: UILabel!
    @IBOutlet weak var convertButton: UIButton!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    //MARK: - Properties
    var selectedCurrency: Double = 0

    //MARK: - View Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        currencyChange()
        createCurrencyPicker()
        createNumberPad()
    }

    //MARK: - Action
    @IBAction func convert() {
        if myValueTextField.text != "" {
            myConvertedValueLabel.text = String(Double(myValueTextField.text!)! * selectedCurrency)
            myConvertedValueLabel.text = String(format: "%.2f")
        }
    }

    @IBAction func dismissKeyboard(_ sender: UITapGestureRecognizer) {
        myValueTextField.resignFirstResponder()
        myCurrencyTextField.resignFirstResponder()
    }

    //MARK: - Methods
    func currencyChange() {
        CurrencyChangeService.shared.getCurrencyChange { (success, rate) in
            self.toggleActivityIndicator(shown: true)
            if success {
                self.toggleActivityIndicator(shown: false)
            } else {
                self.showAlert(title: "Error", message: "Rates download failed!")
            }
        }
    }

    func toggleActivityIndicator(shown: Bool) {
        activityIndicator.isHidden = !shown
        convertButton.isHidden = shown
    }

    func createNumberPad() {
        myValueTextField.keyboardType = UIKeyboardType.numberPad
    }

    func createCurrencyPicker() {
        let currencyPicker = UIPickerView()
        currencyPicker.delegate = self
        myCurrencyTextField.inputView = currencyPicker
    }
}

extension CurrencyChangeViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return CurrencyChangeService.shared.currencies.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        CurrencyChangeService.shared.currencies.sort()
        return CurrencyChangeService.shared.currencies[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedCurrency = CurrencyChangeService.shared.rate[row]
        myCurrencyTextField.text = CurrencyChangeService.shared.currencies[row]
    }
}

在 IB 中,在最右边的按钮上,删除对 @IBAction 转换的引用,然后重新添加。看起来编译器找不到 convert.