(Swift)twilio发布使用alamofire设置属性的请求

时间:2016-08-25 03:46:40

标签: json swift twilio alamofire twilio-api

我正在尝试使用Twilio的REST Api和Alamofire在创建频道时为频道设置某些属性(https://www.twilio.com/docs/api/ip-messaging/rest/channels#action-create

[Service]
Type=forking

使用该代码,我收到的回复是使用FriendlyName foo和UniqueName栏创建了一个Channel,但该Channel没有设置属性。

查看Alamofire github(https://github.com/Alamofire/Alamofire)我发现有一种方法可以发送带有JSON编码参数的POST请求。所以我尝试了这个:

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)
}

在请求中添加“encoding:.JSON”时,响应显示不仅没有设置Attributes,而且FriendlyName和UniqueName也是nil,这与之前使用URL编码参数正确设置时不同。

我是否在'参数'中设置了属性错误? Twilio的文档说“属性”是一个可选的元数据字段,可用于存储您希望的任何数据。不对此字段进行处理或验证。“

帮助将不胜感激:)

1 个答案:

答案 0 :(得分:1)

我已经找到了问题的答案。结果我错误地格式化了属性字段。

以下代码对我有用:

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)
}

希望这有助于其他人:)