2016-08-25 121 views
1

我試圖使用Twilio的REST API和Alamofire創造它(https://www.twilio.com/docs/api/ip-messaging/rest/channels#action-create(SWIFT)twilio POST請求使用alamofire

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欄創建的,但該頻道沒有設置任何屬性。

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

當添加「編碼:以.json」的反應表明,不僅是屬性沒有設置,但也的FriendlyName和UniqueName是零,不像以前的請求時,他們設置正確使用URL編碼參數。

我是否在參數中設置了屬性錯誤? Twilio的文檔說屬性是「一個可選的元數據字段,您可以使用它來存儲您希望的任何數據,而不需要對此字段進行處理或驗證。」

幫助將不勝感激:)

回答

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

希望這會幫助別人:)