noobdev noobdev - 6 months ago 70
iOS Question

Alamofire completion handler issue

I have a POST request with certain data that I would like to receive. However when I use

responseArray
I would be thrown this error


json data is nil


but when I use
responseJSON
everything would be fine. Why is this so?

This code does not work:

Alamofire.request(.POST, Data.todoEndpoint, parameters: parameters)
.responseArray { (response: Response<[Particulars], NSError>) in

print(response.request)
print(response.response)
print(response.result)


if let result = response.result.value
{

do{
print(Realm.Configuration.defaultConfiguration.fileURL)
let realm = try Realm()
realm.add(result, update: true)
}

catch let err as NSError {
print("Error with realm: " + err.localizedDescription)
}

}
else
{
print("JSON data is nil.")
}
}


But this is fine:

Alamofire.request(.POST, Data.todoEndpoint, parameters: parameters)
.responseJSON { response in

print(response.request)
print(response.response)
print(response.result)


if let result = response.result.value
{

print(result)

}
else
{
print("JSON data is nil.")
}
}


I need
responseArray
so that I can have
(response: Response<[Particulars], NSError>)
and store my JSON response into realm

UPDATE

This is the Particulars class that I want to connect to. I'm trying to map my JSON objects to Realm based on this article https://blog.hyphe.me/realm-and-alamofire-in-a-effective-harmony/

import Foundation
import RealmSwift
import ObjectMapper


class Particulars: Object, Mappable {
dynamic var name = ""
dynamic var email = ""
dynamic var id = ""
dynamic var profilePicture = ""
dynamic var username = ""
dynamic var apiToken = ""


override static func primaryKey() -> String? {
return "id"
}

//Impl. of Mappable protocol
required convenience init?(_ map: Map) {
self.init()
}

func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
email <- map["email"]
profilePicture <- map["profile_picture"]
username <- map["username"]
apiToken <- map["api_token"]
}
}


And this is the JSON response:

[
"name" : "Jonny Walker",
"api_token" : "qwertyuiop1234567890",
"profile_picture" : "http:default_profile_picture.jpg",
"id" : 10,
"email" : "jwalker@gmail.com",
"username" : "jonny"
]


UPDATE 2

My completion handler is working fine with
responseObject
but my
realm.add xxx
is throwing up this error


Cannot convert value of type 'String' to expected argument type 'Object'


My code can be found here https://codeshare.io/v4M9M (lines 19- 25)

Answer

The Alamofire page shows how to handle response and does not list the responseArray method. https://github.com/Alamofire/Alamofire#response-serialization

You can use the responseJSON to get the JSON and convert into an array that you want. It would look something like this, (make changes to this based on your JSON response)

Alamofire.request(.POST, Data.todoEndpoint, parameters: parameters)
   .responseJSON { response in

        guard response.result.isSuccess else
        {
              //handle error 
              return
        }

        guard let value = response.result.value as? [String: AnyObject], 
                           particularsArrayJson = value["particulars"] as? [[String: AnyObject]] 
        else{
               //Malformed JSON, handle this case
        }

        var particulars = [Particulars]()
        for particularsDict  in paricularsArrayJson{
              particulars.append(Pariculars(json:particularsDict))
        }
}

You have to have an initializer in your Particulars that will initialise from the JSON provided.

Update:

The realm add method takes an instance of a class which extends from Object Object is a class provided by Realm. So you may have to read up the documentation more.

You should be doing this instead

      realm.add(particulars, updated:true)