2016-08-01 129 views
2

我正在嘗試創建一個應用程序,當您按下按鈕時,它會向預設號碼發送文本消息,並且我正在使用Twilio作爲SMS消息。問題是我正在使用Swift作爲我的應用程序,並且目前它們沒有快速示例。這是我發送消息代碼:Twilio在swift中發送短信

func sendSMS() 
{ 

    let twilioSID = "AC11ed62fdb971a8f56d9be531a5ce40c2" 
    let twilioSecret = "mySecretID" 

    let fromNumber = "number" 
    let toNumber = "number" 
    let message = "This is a test message" 


    // Build the request 
    let request = NSMutableURLRequest(URL: NSURL(string:"https://\(twilioSID):\(twilioSecret)@api.twilio.com/2010-04-01/Accounts/\(twilioSID)/SMS/Messages")!) 
    request.HTTPMethod = "POST" 
    request.HTTPBody = "From=\(fromNumber)&To=\(toNumber)&Body=\(message)".dataUsingEncoding(NSUTF8StringEncoding) 

    // Build the completion block and send the request 
    NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in 
     print("Finished") 
     if let data = data, responseDetails = NSString(data: data, encoding: NSUTF8StringEncoding) { 
      // Success 
      print("Response: \(responseDetails)") 
     } else { 
      // Failure 
      print("Error: \(error)") 
     } 
    }).resume() 
} 

但每當我嘗試運行該功能,我得到這個

Finished 
Response: <?xml version='1.0' encoding='UTF-8'?> 
<TwilioResponse><RestException><Code>20003</Code><Detail>Your AccountSid or AuthToken was incorrect.</Detail><Message>Authentication Error - No credentials provided</Message><MoreInfo>https://www.twilio.com/docs/errors/20003</MoreInfo><Status>401</Status></RestException></TwilioResponse> 

我知道,我的憑據是正確的.....

有沒有更好的方法來做到這一點?有沒有人有一個例子呢?

+2

iOS不會讓您在URL中嵌入用戶名/密碼,因爲它不安全。您需要爲您的請求添加驗證標頭。 – Paulw11

+0

@ Paulw11我會怎麼做呢? Swift是新的,因此網上沒有很多教程 –

回答

1

Matthew,正如上述評論中所述/我們不建議您出於安全原因通過客戶端代碼從REST API發送SMS。

我們建議您包裝您的憑據,並使用在這裏看到的例子可用助手庫的一個在後端應用程序中發送SMS: https://www.twilio.com/docs/api/rest/sending-messages

實際上wrote a post我的一位同事來解決這一對Android社區,看起來我們應該爲Swift做同樣的事情,這會更加快速。

[更新]How to send an SMS from Swift post

希望這會有所幫助。