我刚刚开始使用Swift进行编码,并且在使用Alamofire构建应用程序时遇到了此错误
错误是:
错误:可选(Alamofire.AFError.invalidURL(“”))
这是我的代码。有人可以帮忙吗?
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
let baseURL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTC"
let currencyArray = ["AUD", "BRL","CAD","CNY","EUR","GBP","HKD","IDR","ILS","INR","JPY","MXN","NOK","NZD","PLN","RON","RUB","SEK","SGD","USD","ZAR"]
let currencySymbolsArray = ["$", "R$", "$", "¥", "€", "£", "$", "Rp", "₪", "₹", "¥", "$", "kr", "$", "zł", "lei", "₽", "kr", "$", "$", "R"]
var currencySymbol = ""
var finalURL = ""
//Pre-setup IBOutlets
@IBOutlet weak var bitcoinPriceLabel: UILabel!
@IBOutlet weak var currencyPicker: UIPickerView!
// determine number of columns
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// determine number of rows
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return currencyArray.count
}
// fill in each row with title from array
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return currencyArray[row]
}
// Print something when you select a row
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print (currencyArray[row])
finalURL = baseURL + currencyArray[row]
print(finalURL)
currencySymbol = currencyArray[row]
}
override func viewDidLoad() {
super.viewDidLoad()
currencyPicker.delegate = self
currencyPicker.dataSource = self
getCurrencyData(url: finalURL)
}
//TODO: Place your 3 UIPickerView delegate methods here
// //MARK: - Networking
// /***************************************************************/
func getCurrencyData(url: String) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
print("Success! Got the currency data ")
let currencyJSON : JSON = JSON(response.result.value!)
self.updateCurrencyData(json: currencyJSON)
} else {
print("Error: \(String(describing: response.result.error))")
self.bitcoinPriceLabel.text = "Connection issues"
}
}
}
// //MARK: - JSON Parsing
// /***************************************************************/
func updateCurrencyData(json : JSON) {
if let currencyResult = json["ask"].double {
bitcoinPriceLabel.text = " \(currencySymbol) + \(currencyResult) "
} else {
bitcoinPriceLabel.text = "Currency unavailable"
}
}
}
答案 0 :(得分:0)
问题是您正在从视图控制器getCurrencyData
方法调用viewDidLoad
,而finalURL
的值仍是其初始值,即""
,即完全是您在错误消息中看到的无效URL。
您只需要在用户使用选择器实际进行选择后就可以拨打网络电话。
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
currencySymbol = currencySymbolsArray[row]
getCurrencyData(url: baseURL + currencyArray[row])
}
也不需要finalURL
变量,因为您可以将finalURL
中存储的数据直接输入到getCurrencyData
函数中。
与错误无关,但是您还为currencySymbol
设置了错误的数据,因为您是从currencyArray
而不是currencySymbolArray
为其分配数据。