首页 > 解决方案 > 我需要接受 alamofire 关闭的响应并将其发送到另一个班级

问题描述

我需要接受 alamofire 关闭的响应并将其发送到另一个班级。我在闭包内得到响应,但是当我尝试发送到另一个类时,我得到:“致命错误:在展开可选值时意外发现 nil

我需要从闭包中获取响应并将其设置在另一个类的 IBOutlet 中。

此外,我尝试在全局变量中设置关闭响应,但我得到了同样的错误。

class DrawInformationViewController: UIViewController {
   @IBOutlet weak var nameLabel: UILabel!

   override func viewDidLoad() {
       super.viewDidLoad()

  }
}

class RequestViewController: UIViewController{
    var getName: String?
    func testAlamofire(){
       if let JSON = response.result.value{
       self.jsonArray = JSON as? NSArray
       //this for doesn't matter it is just for an example, to get the idea
       for item in self.jsonArray! as! [NSDictionary]{
          let name = item["name"] as? String
          print(name) //until here everything is ok
          //the problem is when I try to send this value
          DrawInformationViewController().nameLabel.text = name //here is when it get the error: "Fatal error: Unexpectedly found nil while unwrapping an Optional value"
          //Also I try to set the value in a global var
          getName = name //There is not problem
       }
      }
    }
  }
  func setValueFromClosure(){
     DrawInformationViewController().nameLabel.text = getName
     //Here I get the same error: "Fatal error: Unexpectedly found nil while unwrapping an Optional value" 
  } 
}

标签: iosswiftclosuresalamofire

解决方案


尝试按如下方式初始化 getName:

变量 getName: 字符串 = ""

干杯。


推荐阅读