Alamofire.request().responseObject doesn't return response

825 views Asked by At

I use AlamofireObjectMapper extension. I want to get response, but it's failed. My tableLeague object is always nil because code with response closure doesn't call ({ (response: DataResponse) in if response.result.isSuccess { tableLeague = response.result.value } doesn't call). I use next methods:

let header = ["X-Auth-Token":"1231231"]

static let sharedInstance = ServerAPI()
private func getRequest(uri: String) -> DataRequest {
    return Alamofire.request(uri, method: .get, headers: header)
}

public func getTableLeague() -> TableLeague {
    var tableLeague: TableLeague?
    getRequest(uri: URL).responseObject { (response: DataResponse<TableLeague>) in
        if response.result.isSuccess {
            tableLeague = response.result.value
        }
    }
    return tableLeague!
}

And use in business class:

public func readTableLeague() -> TableLeague {
    let tableLeague = ServerAPI.sharedInstance.getTableLeague()
    return tableLeague
}

I think it can be because response haven't yet but i try to set object that i haven't yet

Whats a problem? Completion handlers i need to use else?

1

There are 1 answers

0
Usman Javed On

Please try to map by following structure

class Response: Mappable {
    var success: Bool?
    var data: [Data]?

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        success <- map["success"]
        data <- map["data"]
    }
}

class Data: Mappable {
    var uid: Int?
    var name: String?
    // add other field which you want to map        

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        uid <- map["uid"]
        name <- map["name"]
    }
}

When you get JSON response simple map by this syntax

let response = Mapper<Response>().map(responseObject)
if let id = response?.data?[0].uid {
    println(id)
}