I tried a lot of methods from stackoverflow and from googling but I got no luck of reaching what I need.
simply I want to store the response from api request to some variable so that I can use it freely.
here is the code
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var responseLabel: UILabel!
let apiUrlStr = "http://jsonplaceholder.typicode.com/posts"
var resData = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
request(.GET, apiUrlStr, encoding: .JSON).responseJSON { (_, _, JSON, _) in
let arr = JSON as NSArray
let user = arr[0] as NSDictionary
self.responseLabel.text = user.objectForKey("title") as? String
self.resData = JSON as NSArray //i cant get this from outside
}
println(resData) //prints nothing but empty parentheses while inside the request it prints the data right
}
}
because I have multiple classes and every class need to handle the response in a different way I want to create an api class with a response method that will return the response.
something like this maybe:
class api{
func req(url: String, params: NSDictionary){
//method goes here
}
func res() -> NSDictionary{
//method goes here
var response = NSDictionary()
return response
}
}
then use it like this in viewdidload
let params = ["aaa","bbb"]
let api = api()
api.req(apiUrlStr, params)
let res = api.res()
***by the way the request method I'm using right now is from Alamofire.swift and I dont mind using another method
here is some of the posts and sites I tried to follow without a luck
proper-way-to-pull-json-api-resoponse
all lead to the same result response only from inside the method.