简体   繁体   English

错误:可选(Alamofire.AFError.invalidURL(“”))

[英]Error: Optional(Alamofire.AFError.invalidURL(“”))

I am just starting to code with Swift, and I came across this error while building an app using Alamofire 我刚刚开始使用Swift进行编码,并且在使用Alamofire构建应用程序时遇到了此错误

The error is : 错误是:

Error: Optional(Alamofire.AFError.invalidURL("")) 错误:可选(Alamofire.AFError.invalidURL(“”))

This is my code. 这是我的代码。 Can someone help?? 有人可以帮忙吗?

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"
        }
    }
}

The issue is that you are calling getCurrencyData from your view controllers viewDidLoad method, while the value of finalURL is still its initial value, namely "" , which is exactly what you see as the invalid URL in the error message. 问题是您正在从视图控制器的viewDidLoad方法中调用getCurrencyData ,而finalURL的值finalURL是其初始值,即"" ,这恰好是您在错误消息中看到的无效URL。

You only need to make the network call once the user actually makes a selection using the picker. 用户实际使用选择器进行选择后,只需拨打网络电话即可。

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    currencySymbol = currencySymbolsArray[row]
    getCurrencyData(url: baseURL + currencyArray[row])
}

There's also no need for the finalURL variable, since you can directly input the data you stored in finalURL to the getCurrencyData function. 也不需要finalURL变量,因为您可以将存储在finalURL的数据直接输入到getCurrencyData函数中。

Unrelated to the error, but you were also setting wrong data to currencySymbol , since you were assigning data to it from the currencyArray rather than the currencySymbolArray . 与错误无关,但是您还为currencySymbol设置了错误的数据,因为您是从currencyArray而不是currencySymbolArray为其分配数据的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 快速的Alamofire InvalidURL - Alamofire InvalidURL in swift Alamofire+Combine:如何从 AFError 中获取自定义错误类型 - Alamofire+Combine: how to get custom error type out of AFError Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域=NSCocoaErrorDomain 代码=3840 - Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 操作无法完成。 (Alamofire.AFError 错误 9。) - The operation could not complete. (Alamofire.AFError error 9.) Swift 5 &amp; Alamofire 5:GET 方法错误:Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(22 bytes) - Swift 5 & Alamofire 5 : GET method ERROR: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(22 bytes) Alamofire:responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) - Alamofire: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) Alamofire - Alamofire.AFError.responseSerializationFailed - Xcode 8 - Alamofire - Alamofire.AFError.responseSerializationFailed - Xcode 8 使用Flickr API时Alamofire AFError - Alamofire AFError when work with Flickr API “结果”类型的 Alamofire 值<any, aferror> ' 没有成员 'isSuccess' (Swift 5)</any,> - Alamofire Value of type 'Result<Any, AFError>' has no member 'isSuccess' (Swift 5) 失败:responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) - FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM