单击“完成”按钮与pickerView组合后,请求服务器

时间:2018-10-25 09:25:53

标签: ios swift

很抱歉,可能有一个太长的问题,但是我刹车了两天,不明白为什么它会起作用。因此,我有测试应用程序,通过它可以学习Swift的学习能力和功能。该应用程序的主要功能显示某种货币的某种加密硬币的价值。

1

当我在pickerView中将其组合时,它可以正常工作。但是,我决定添加以下功能,该功能必须使硬币数量成倍增加。当我在数字键盘上输入一些数字并单击“完成”时,应用程序会向我显示一些神秘的数字。

2

3

我不知道为什么会这样。按照应用程序的逻辑,在单击“完成”后,它必须向服务器发出请求,并获得硬币的价值并将其相乘。但事实并非如此。

4

仅在我开始在pickerView中旋转字符串后,它才会发送请求。

5

6

如果有人花时间解决这个问题,将非常感激。

import UIKit 
import Foundation
import Alamofire
import SwiftyJSON

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {

let baseURL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/"
let coinArray = ["BTC", "ETH", "XRP", "BCH", "LTC"]
let currencyArray = ["EUR", "PLN", "RUB", "USD", "UAH"]
let currencySymbol = ["€", "zł", "₽", "$", "₴"]
var rowForASymbol: Int = 0
var finalURL = ""
var globalCoinValue: Float?

@IBOutlet weak var bitcoinPriceLabel: UILabel!
@IBOutlet weak var currencyPicker: UIPickerView!
@IBOutlet weak var valueTextField: UITextField!

override func viewDidLoad() {

    super.viewDidLoad()

    bitcoinPriceLabel.text = ""

    currencyPicker.delegate = self //the delegate for the picker view
    currencyPicker.dataSource = self //the data source for the picker view
    valueTextField.delegate = self
    self.addDoneButtonOnKeyboard()

    getBitcoinData(url: baseURL + coinArray[0] + currencyArray[0])

}

//MARK: - Configuration pickerView
//number of columns of data
func numberOfComponents(in pickerView: UIPickerView) -> Int {

    return 2

}

//number of rows of data
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if component == 0 {

        return coinArray.count

    } else {

        return currencyArray.count

    }

}

//fill the picker row titles with the Strings from currencyArray
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    if component == 0 {

        return coinArray[row]

    } else {

        return currencyArray[row]

    }

}

//which row user selected
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    var coin = coinArray[pickerView.selectedRow(inComponent: 0)]
    var currency = currencyArray[pickerView.selectedRow(inComponent: 1)]

    if component == 0 {

        coin = coinArray[row]

    } else {

        rowForASymbol = row
        currency = currencyArray[row]

    }

    finalURL = baseURL + coin + currency

    getBitcoinData(url: finalURL)

}

//MARK: - Networking (Alamofire)
//part that's going to make the HTTP request for the data
func getBitcoinData(url: String) {

    Alamofire.request(url, method: .get).responseJSON {

        response in
        if response.result.isSuccess {

            print("Success! Got the bitcoin data")

            let bitcoinJSON: JSON = JSON(response.result.value!)

            self.updateBitcoinData(json: bitcoinJSON)

        } else {

            print("Error \(String(describing: response.result.error))")
            self.bitcoinPriceLabel.text = "Connection Issues"

        }

    }

}

//MARK: - JSON Parsing (SwiftyJSON)
//passes the response that we get from bitcoinaverage into something that we can display in our app
func updateBitcoinData(json: JSON) {

    if let coinValue = json["ask"].float {

        if valueTextField.hasText {

            doneButtonAction(globalCoinValue: coinValue)

        } else {

        bitcoinPriceLabel.text = "\(coinValue) \(currencySymbol[rowForASymbol])"

        }

    } else {

        bitcoinPriceLabel.text = "Data unavailable"

    }

}

func addDoneButtonOnKeyboard()
{
    let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
    doneToolbar.barStyle = UIBarStyle.default

    let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
    let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(self.doneButtonAction(globalCoinValue:)))

    var items = [UIBarButtonItem]()
    items.append(flexSpace)
    items.append(done)

    doneToolbar.items = items
    doneToolbar.sizeToFit()

    self.valueTextField.inputAccessoryView = doneToolbar

}

@objc func doneButtonAction(globalCoinValue: Float) {

    if let valueInTextField = valueTextField.text {

        print("valueInTextField: \(valueInTextField)")
        let mulValue = Float(valueInTextField)! * globalCoinValue
        bitcoinPriceLabel.text = "\(mulValue) \(currencySymbol[rowForASymbol])"
        print("globalCoinValue: \(globalCoinValue)")
        print("mulValue: \(mulValue)")

    }

    self.valueTextField.resignFirstResponder()

}

}

1 个答案:

答案 0 :(得分:0)

问题是,当您按“完成”时,不会触发getBitcoinData(url: finalURL)

假设在按下按钮时触发了@objc func doneButtonAction(globalCoinValue: Float),则可以通过添加以下几行来来解决您的问题:

 var coin = coinArray[currencyPicker.selectedRow(inComponent: 0)]
 var currency = currencyArray[currencyPicker.selectedRow(inComponent: 1)]
 finalURL = baseURL + coin + currency
 getBitcoinData(url: finalURL)

@objc func doneButtonAction(globalCoinValue: Float),就像下面的代码一样

@objc func doneButtonAction(globalCoinValue: Float) {
    if let valueInTextField = valueTextField.text {

        print("valueInTextField: \(valueInTextField)")
        let mulValue = Float(valueInTextField)! * globalCoinValue
        bitcoinPriceLabel.text = "\(mulValue) \(currencySymbol[rowForASymbol])"
        print("globalCoinValue: \(globalCoinValue)")
        print("mulValue: \(mulValue)")

    }

    self.valueTextField.resignFirstResponder()

    var coin = coinArray[currencyPicker.selectedRow(inComponent: 0)]
    var currency = currencyArray[currencyPicker.selectedRow(inComponent: 1)]
    finalURL = baseURL + coin + currency
    getBitcoinData(url: finalURL)

}