【问题标题】:How can I send fetched data to my ViewController?如何将获取的数据发送到我的 ViewController?
【发布时间】:2020-11-11 19:56:13
【问题描述】:

这是我的 API 调用的标题:

所以,我已经拥有了我需要的口袋妖怪的能力,但是现在,我想知道如何从我的 Service 类(我正在执行所有解析)中获取这些数据,并将其发送到我的 InfoViewController。

我的目的是在某个标签上获取该数据,然后根据他们的 ID 显示每个 poke 的能力名称。这是我的应用程序的标题:

我想在体重下方添加一个“能力”标签,这就是我想分配数据的地方。我有一个包含所有口袋妖怪的完整 CollectionView,目标是为每个口袋妖怪分配正确的能力。

我正在努力寻找一种实用(且不那么冗长)的方法来实现这一目标。

我也感谢每一条评论、任何建议和建议。谢谢!

编辑:这是我的代码:

extension InfoController: ServiceDelegate {
        
    func finishedWithPokemonAbilities(abilities: [String], id: Int) {
        
        self.abilities = abilities
        self.ids = id
        
        print(abilities)
        
    }
}

【问题讨论】:

  • 请不要显示代码图片。代码是文本。将您的代码复制并粘贴到问题中。谢谢。

标签: swift parsing fetch-api pokeapi


【解决方案1】:

您可以创建一个自定义Protocol(可以称为PokemonServiceDelegate 作为示例),您的InfoViewController 将继承和实现。在您的服务对象上(我在示例中使用PokemonService)创建一个类型为PokemonServiceDelegate 的属性并将该属性设置为您想要接收数据的视图控制器。服务完成获取数据后,通过在协议中声明的函数中传递数据来更新委托。

// Protocol your view controller will inherit
protocol PokemonServiceDelegate {
    // Function your view controller will implement
    func finishedWithPokemonAbilities(abilities: [String])
}

class InfoViewController: UIViewController {
    // Reference to the service that makes the request
    var service: PokemonService
    override func viewDidLoad() {
        ...
        // Set the delegate of the service to self
        service.delegate = self
        ...
    }
}

extension InfoViewController: PokemonServiceDelegate {
    // Implement the protocol
    func finishedWithPokemonAbilities(abilities: [String]) {
        // Do something with their abilities here
    }
}

struct PokemonService {
    var delegate: PokemonServiceDelegate?
    // The function that you call to get your abilities
    func someUpdateFunc() {
        ...
            let abilities = json[abilities].arrayValue.map {$0["ability"]["name"].stringValue}

            delegate?.finishedWithPokemonAbilities(abilities: abilities)
        ...
    }
}

【讨论】:

  • 现在,当我打印数据以检查是否得到它时,它不会在控制台上返回任何内容。为什么会这样?我用一些代码更新了我的帖子。
  • 你是从你的服务对象调用delegate?.finishedWithPokemonAbilities(abilities: abilities)吗?
猜你喜欢
  • 2019-11-06
  • 1970-01-01
  • 2018-10-05
  • 2015-07-15
  • 2019-08-12
  • 2023-03-31
  • 1970-01-01
  • 2014-05-24
  • 1970-01-01
相关资源
最近更新 更多