【问题标题】:How to access data outside the Alamofire block using swift 3.0如何使用 swift 3.0 访问 Alamofire 块之外的数据
【发布时间】:2017-05-24 12:42:11
【问题描述】:

我刚刚开始使用“Alamofire”进行 JSON 解析。现在我面临一些问题如下:

问题说明:无法访问 Alamofire 块之外的数据。

编码材料:

import UIKit

import Alamofire

    class ViewController: UIViewController
    {
        var dataValue = String()
        override func viewDidLoad()
        {
            super.viewDidLoad()
            Alamofire.request("url") .responseJSON 
            { response in

                dataValue = response.result.value
                print(dataValue) // It prints value
            }
            print(dataValue) //It does not print any thing or nil.
        }

    }

【问题讨论】:

  • 提示:寻找completionHandler:
  • 请给我一些例子,完成处理程序,因为我是新手。
  • @Ashish 它没有完成部分,请查看我的答案
  • Ashish,IDT 这些答案将满足您的实际目的。

标签: ios json swift3 alamofire


【解决方案1】:
 var dataValue = String()
 override func viewDidLoad()
 {
   super.viewDidLoad()
   Alamofire.request("url") .responseJSON 
  { response in

     dataValue = response.result.value
     self.myFunction(str: dataValue)
  }
  }

 func myFunction(str: String)
 {
    print("str value ====%@",str)
 }

【讨论】:

  • 谢谢,现在我明白了。如何访问 Alamofire 之外的数据。
  • 您好,它解析 JSON 数据并更新 UIView 非常缓慢。为什么会发生这种情况?
【解决方案2】:

Alamofire 使用块来获取 web API 的所以根据你的问题。您可以通过将断点放入块和块后进行检查。

class ViewController: UIViewController
    {
        var dataValue = String()
        override func viewDidLoad()
        {
            super.viewDidLoad()
            Alamofire.request("url") .responseJSON 
            { response in

                dataValue = response.result.value
                print(dataValue) // It prints value
            }
            print(dataValue) //It does not print any thing or nil.
        }

    }

该行不打印任何内容,因为它会首先进行调试,而您的 alamofire 块会调试并在您获得响应时返回,它会打印值。

所以我认为你可以将 dataValue 的值用于另一个函数,因为它在将响应放入块后存储。

希望这会对你有所帮助。

【讨论】:

  • 感谢@Jecky 的回答。
  • 你是对的,首先是在 Alamofire 调试之外的变量,然后是 Alamofire,这就是它打印 nil 的原因。
【解决方案3】:

Alamofire 块是一个异步回调。换句话说,只要响应准备好,它就会运行完成块。 如果您想在设置时使用dataValue。您可以在变量属性中利用didSet

class ViewController: UIViewController
{
    var dataValue = String() {
       didSet {
           // do something here
           print(dataValue) // It prints value 
       }
    }
    override func viewDidLoad()
    {
        super.viewDidLoad()
        Alamofire.request("url") .responseJSON 
        { response in

            dataValue = response.result.value
            print(dataValue) // It prints value 
        }
        print(dataValue) //It does not print any thing or nil.
    }

}

【讨论】:

    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多