2017-01-10 30 views
2

我剛剛開始用於JSON分析的'Alamofire'。現在我正面臨一些問題,如下所示:如何使用swift訪問Alamofire區塊以外的數據3.0

問題聲明:無法訪問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. 
     } 

    } 
+1

提示:查找'completionHandler:' –

+0

請爲我提供一些示例,完成處理程序,因爲我是新手。 –

+0

@Ashish它沒有完成部分,請檢查我的答案 –

回答

2
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) 
} 
+0

謝謝,現在我明白了。如何訪問Alamofire以外的數據。 –

+0

你好,它解析JSON數據和非常緩慢地更新UIView。爲什麼發生這種情況? –

1

Alamofire使用塊用於獲取網絡的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的值到另一個函數中,因爲它在獲得響應後存儲。

希望這會幫助你。

+0

謝謝@Jecky的回答。 –

+0

你是對的,首先在Alamofire調試之外變量,然後Alamofire,這就是爲什麼它打印零。 –

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

} 
+0

謝謝,這也適用。 –

相關問題