Search code examples
jsonswifttwilioalamofiretwilio-api

(Swift) twilio post request to set attributes using alamofire


I am attempting to use Twilio's REST Api and Alamofire to set certain Attributes to a Channel when creating it (https://www.twilio.com/docs/api/ip-messaging/rest/channels#action-create)

let parameters : [String : AnyObject] = [
    "FriendlyName": "foo",
    "UniqueName": "bar",
    "Attributes": [
        "foo": "bar",
        "bar": "foo"
    ],
    "Type": "private"
]

Alamofire.request(.POST, "https://ip-messaging.twilio.com/v1/Services/\(instanceSID)/Channels", parameters: parameters)
    .authenticate(user: user, password: password)
    .responseJSON { response in
        let response = String(response.result.value)
        print(response)
}

Using that code, the response I received back was that a Channel was created with FriendlyName foo and UniqueName bar, but that Channel had no Attributes set.

Looking at the Alamofire github (https://github.com/Alamofire/Alamofire) I see that there's a way to send a POST Request with JSON-encoded Parameters. So I tried this:

let parameters : [String : AnyObject] = [
    "FriendlyName": "foo",
    "UniqueName": "bar15",
    "Attributes": [
        "foo": "bar",
        "bar": "foo"
    ],
    "Type": "private"
]

Alamofire.request(.POST, "https://ip-messaging.twilio.com/v1/Services/\(instanceSID)/Channels", parameters: parameters, encoding: .JSON)
    .authenticate(user: user, password: password)
    .responseJSON { response in
        let response = String(response.result.value)
        print(response)
}

When adding "encoding: .JSON" to the request the response shows that not only were the Attributes not set but also the FriendlyName and UniqueName were nil, unlike before when they were correctly set using the URL-Encoded Parameters.

Am I setting the Attributes wrong in 'parameters'? Twilio's documentation says that Attributes is "An optional metadata field you can use to store any data you wish. No processing or validation is done on this field."

Help would be appreciated :)


Solution

  • I have figured out an answer to my question. Turns out I had formatted the Attributes field incorrectly.

    Here is the code that worked for me:

    let parameters : [String : AnyObject] = [
        "FriendlyName": "foo",
        "UniqueName": "bar",
        "Attributes": "{\"key\":\"value\",\"foo\":\"bar\"}",
        "Type": "private"
    ]
    
    Alamofire.request(.POST, "https://ip-messaging.twilio.com/v1/Services/\(instanceSID)/Channels/", parameters: parameters)
        .authenticate(user: user, password: password)
        .responseJSON { response in
            let response = String(response.result.value)
            print(response)
            debugPrint(response)
    }
    

    Hope this helps others :)