【问题标题】:(Swift) twilio post request to set attributes using alamofire(Swift) twilio 发布请求以使用 alamofire 设置属性
【发布时间】:2017-01-01 08:38:45
【问题描述】:

我正在尝试使用 Twilio 的 REST Api 和 Alamofire 在创建通道时为通道设置某些属性 (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)
}

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

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

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

向请求中添加“encoding: .JSON”时,响应显示不仅未设置属性,而且 FriendlyName 和 UniqueName 均为零,这与之前使用 URL 编码参数正确设置时不同。

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

我们将不胜感激:)

【问题讨论】:

    标签: json swift twilio alamofire twilio-api


    【解决方案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)
    }
    

    希望这对其他人有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多