【问题标题】:Swift 3 Send HTTP Request Result to UIViewControllerSwift 3 向 UIViewController 发送 HTTP 请求结果
【发布时间】:2017-02-16 15:22:50
【问题描述】:

我正在发送一个 HTTP 请求。如果结果成功,我希望它显示在第二个 UIViewController 上。但是,如果失败,我想在原始 UIViewController 上显示失败。

let parameters: Parameters = [
        "x": 2,
        "y": 2
    ]

    Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
        if((response.result.value) != nil) {
            let secondViewController:SecondViewController = SecondViewController()
            self.present(secondViewController, animated: true, completion: nil)
            let jsonVar: JSON = JSON(response.result.value!)
            secondViewController.jsonDisplayResult.text = "\(jsonVar)"
        } else {
            self.jsonDisplayError.text = "no response"
        }
    }

我已经创建了第二个 ViewController 和一个标签来显示结果。我收到此错误:致命错误:在展开可选值 (lldb) 时意外发现 nil。

【问题讨论】:

  • 你调用 Alamofire 请求方法的上下文是什么?
  • 两个整数作为参数传入。 POST 请求将返回两个整数之和。如果一个整数为 null 则返回 Invalid Response
  • 它在哪一行崩溃了?是让 jsonVar: JSON = JSON(response.result.value!) 。如果是这样,因为 response.result.value 是 nil 并且 !表示不为零。
  • 它在这一行崩溃:"secondViewController.jsonDisplayResult.text = "(jsonVar)""
  • 能否在secondViewController.jsonDisplayResult.text = "\(jsonVar)"添加断点并上传Debug Navigator的截图?

标签: ios uiviewcontroller swift3 httprequest


【解决方案1】:

试试这个:

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { (response: DataResponse<Any>) in
    if let response = response.result.value as? <insert Type of value> {
        let secondViewController:SecondViewController = SecondViewController()
        secondViewController.responseText = response
        self.present(secondViewController, animated: true, completion: nil)

    } else {
        self.jsonDisplayError.text = "no response"
    }
}

并且还在你的 secondViewController 中创建一个新的 var responseText 并在 viewDidLoad 中分配 jsonDisplayResult.text = resonseText,因为你的 jsonDisplayResult 标签很可能。在您尝试将文本属性分配给它的状态下为 nil。

【讨论】:

  • 我能够让它进入下一个屏幕。但是,UILabel 字段中没有出现任何内容。
  • 在什么时候分配 label.text (viewDidLoad)?
【解决方案2】:

我的猜测是 jsonDisplayResultUILabelUITextField 或类似的东西,通过 IBOutlet 连接,它是 nil 因为你已经将你的 secondViewController 实例化为 SecondViewController(),它赢了'不要设置任何出口。

尝试从情节提要中实例化。确保在情节提要中正确设置标识符。

let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController

编辑:

点击您的 SecondViewController 后,在此处设置 Storyboard ID:

【讨论】:

  • 我得到“在闭包中隐式使用 self;使用 self。”当我切换到 self 时,我得到“ViewController 类型的值没有成员 instantiateViewController”
  • 2017-02-16 10:46:08.132 HTTPRequest[36936:289563] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“故事板()没有” t 包含标识符为“SecondViewController”的视图控制器
  • 我引用:“确保在情节提要中正确设置标识符。”
  • 我修复了 Storyboard ID,但出现此错误:“致命错误:在展开可选值时意外发现 nil”
猜你喜欢
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多