Search code examples
iosjsonswift3alamofire

How to access data outside the Alamofire block using swift 3.0


I've just started 'Alamofire' for JSON parsing. Now I'm facing some problem which are as follow:

Problem Statement : Unable to access data outside the Alamofire block.

Coding Stuff :

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

    }

Solution

  •  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)
     }