Ron Pelayo February 2016

How to wrapped JSON Handler in Function

So I'm using this function to pass the JSON Value (Any Object) in other class but it's full of issues so I can't get it working

func getSWPeopleAPI() -> NSMutableArray {
    var JSON2: NSMutableArray
    Alamofire.request(.GET, "http://swapi.co/api/people/1").responseJSON { Response in
        print(Response.request)
        print(Response.response)
        print(Response.data)
        print(Response.result)
        if let JSON = Response.result.value{
            JSON2 = JSON as! NSMutableArray
        }
        else{
            return
        }

    }
    return JSON2
}

Do you have a suggestion on how can I achieve this to pass it to my ApiManagerClass and what data type is best use when dealing with JSON?

Answers


Sohil R. Memon February 2016

You are doing in a wrong way! JSON must have a type of NSDictionary.

func getSWPeopleAPI(strUrl: String, completionHandler: (NSDictionary?, NSError?) -> ()) -> (){

    Alamofire.request(.GET, strUrl).responseJSON { response in

        switch response.result {

        case .Success(let data):
            let json = data as? NSDictionary
            completionHandler(json, nil)
        case .Failure(let error):
            completionHandler(nil, error)
        }
    }

Here is the code with completion handler and error as specified!

How to Use:

postWebserviceWithURL(Url!) { (responseData, error) -> () in

   //Code
}

Post Status

Asked in February 2016
Viewed 3,399 times
Voted 5
Answered 1 times

Search




Leave an answer