Alamofire request to twilio swift - ios

I'm trying to get an SMS from twilio.com but get nil in response. Can anyone say what I'm doing wrong?
class SMSVerificationService: NSObject {
static let sharedInstance = SMSVerificationService()
func SMSRequest(countryCode:String, phoneNumber: String) {
let accountSid = "ACc4d9785419f144412823ff20as34660c3d"
let authToken = "4wqecx41f8999caa23735da214" // changed :)
let url = URL(string: "https://\(accountSid):\(authToken)#api.twilio.com/2010-04-01/Accounts\(accountSid)/Messages")
print("url", url!)
let parameters = [
"To": "+37378847884",
"From" : "+14243960339",
"Body": "Hi daddy"
]
Alamofire.request(url!, method: .post, parameters: parameters,
encoding: JSONEncoding.default, headers: [:]).responseJSON { response in
let response = String(describing: response.result.value)
print(response)
}
}
}

Twilio developer evangelist here.
We do not recommend that you make requests to the Twilio API directly from your native application. To do so, you would need to store or retrieve your account SID and auth token in the application somewhere. If you do this, then a malicious attacker could get access to your credentials and abuse your Twilio account.
This is actually known as the Eavesdropper vulnerability and was written about earlier this year.
Instead we recommend that you create a web application and send the API requests from there. There is a blog post on how to do that here: https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html
I notice that your class is called SMSVerificationService too. If you are looking to build phone verification, then I recommend you take a look at the Twilio Verify API that does a lot of the work for you.

Related

UAE: Voice/Video Calling using Data/WiFi in App - using Swift 4.0

I want to add the Voice/Video calling functionality in my iOS app using Swift 4.0.
which are the third party frameworks I can refer?
Also, I came across the news that VoIP is blocked in many countries
UAE is one of them. Can I achieve the calling features in UAE if YES
then How? My app will be only used in UAE country.
I refered: https://www.quora.com/Is-there-any-VoIP-that-still-works-in-Dubai-in-2018
https://www.twilio.com/blog/2018/03/making-phone-calls-in-swift-with-twilio.html
import Foundation
import Alamofire
if let accountSID = ProcessInfo.processInfo.environment["TWILIO_ACCOUNT_SID"],
let authToken = ProcessInfo.processInfo.environment["TWILIO_AUTH_TOKEN"] {
let url = "https://api.twilio.com/2010-04-01/Accounts/\(accountSID)/Calls"
let parameters = ["From": "YOUR_TWILIO_NUMBER", "To": "YOUR_PERSONAL_NUMBER", "Url": "YOUR_TWIML_URL"]
Alamofire.request(url, method: .post, parameters: parameters)
.authenticate(user: accountSID, password: authToken)
.responseJSON { response in
debugPrint(response)
}
RunLoop.main.run()
}

Alamofire POST request with nested parameters returns nothing

Hello I am trying to use Alamofire for my HTTP requests. It is working with parameters that are not included any nested parameter. Normally, my url is working with following on the Google Chrome.
http://111.222.33.4:12345/my_server/dispatch?cmd=ext_getReferanceData&jp=%7b%22rfName%22:%22RF_ABC%22%7d&token=123
and the decoded version of above url is
http://111.222.33.4:12345/my_server/dispatch?cmd=ext_getReferanceData&jp={"rfName":"RF_ABC"}&token=123
It works fine when I paste it into any browser. However when I try to send following post request with Alamofire
let parameters3: [String: Any] = [
"cmd": "ext_getReferanceData",
"jp": [
"rfName": "RF_ABC"
],
"token": "123"
]
Alamofire.request("http://111.222.33.4:12345/my_server/dispatch", method: .get, parameters: parameters3, encoding: JSONEncoding.default).responseJSON { (response) in
}
It is returning
FAILURE:
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
What could be the reason of it am I sending parameters wrong or is there anything that I am missing?
Edit: I also checked other questions about the error but the problem is about parameters that I am trying to send because there is " and { in the parameters but I could not send in the request.
have you considered printing the response being sent and confirming it that it's indeed the stuff you're trying to send?
You can do a couple of things to improve
Make the method .post
Try to use .validate() for added reliability
The way I do it is something like:
let submissionURL = URL(string: "https://blablabla.com/script.php")
sendAlamofireRequest(submissionURL: submissionURL!, parameters: parameters, chosenTrackerStr: chosenTrackerString) //function call
//function declaration
func sendAlamofireRequest(submissionURL: URL, parameters: Parameters, chosenTrackerStr: String){
Alamofire.request(submissionURL, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseString() { (response) in
//actual code goes here
}
}
Maybe try to play around with the alamofire request and check its documentation to see the suggested approach :)

twilio A 'From' phone number is required swift

I'm trying to get sms from twilio service but keep getting this error.
Request:
func SMSRequest(countryCode:String, phoneNumber: String) {
let accountSid = "ACc4d9785419f144412823ff2034660c3d"
let authToken = "a2293a42841f8999caa237er363" // changed
let phoneNumber = "+14243960339"
let toNumber = "+37378847884"
let url = URL(string: "https://\(accountSid):\(authToken)#api.twilio.com/2010-04-01/Accounts/\(accountSid)/SMS/Messages")
print("url", url!)
let parameters = [
"From": phoneNumber,
"To": toNumber,
"Body":"Hi daddy"
]
Alamofire.request(url!, method: .post, parameters: parameters,
encoding: JSONEncoding.default, headers: [:]).responseJSON { response in
let response = String(describing: response.result.ifFailure({
print(response)
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {print("Data: \(utf8Text)")}
}))
}
}
Error:
<TwilioResponse><RestException><Code>21603</Code><Message>A 'From' phone number is required.</Message><MoreInfo>https://www.twilio.com/docs/errors/21603</MoreInfo><Status>400</Status></RestException></TwilioResponse>
All the credentials I get from here
Solution:
use utf8 encoding.
Twilio developer evangelist here.
It's important to note that, even though you have solved your problem, you are building a fundamentally insecure application. I left this comment on your other question, but I need to point it out here too.
We do not recommend that you make requests to the Twilio API directly from your native application. To do so, you would need to store or retrieve your account SID and auth token in the application somewhere. If you do this, then a malicious attacker could get access to your credentials and abuse your Twilio account.
This is actually known as the Eavesdropper vulnerability and was written about earlier this year.
Instead we recommend that you create a web application and send the API requests from there. There is a blog post on how to do that here: https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html
Update for Swift 4 - you don't really need to specify encoding, just leave it as a default.
Regarding the Twilio answer, they shouldn't say that people "shouldn't" make requests to their API, but rather remove that functionality per se and make a proper authentication service on their SDK. For now this works as the best solution I found.
let accountSID = "BOB"
let authToken = "BOB'S PASSWORD"
let url = "https://api.twilio.com/2010-04-01/Accounts/\(accountSID)/Messages" as URLConvertible
let parameters = ["From": "SENDER", "To": "RECIPIENT", "Body": "Hello world!"]
Alamofire.request(url, method: .post, parameters: parameters)
.authenticate(user: accountSID, password: authToken)
.responseString { response in
debugPrint(response)
}

log in yii2 account using Alamofire

I'm trying to log in into account using api and POST request in Swift 3 with Alamofire library. Here is my code:
#IBAction func logInButtonClick(_ sender: Any) {
Alamofire.request(".../api/login", method: .post, parameters: ["email": "mail1#gmail.com", "password" : "qwerty"], encoding: JSONEncoding.default).responseString { (response) in
if let result = response.result.value {
print(result)
}
}
}
When I'm trying to get an access_token field (user exists and api works correctly, for sure) from this request, I am not getting it.
The fact is my api user's url is always the same (I've already read this: How to pass access token to Alamofire?) and looks like ".../api/login/" and it doesn't depend on user e-mail or username, and I don't know how I should deal with it in a such way. Thanks in advance.

Twilio Send SMS in swift

I'm trying to make an app that when you press a button it sends a text message to a preset number, and I am using Twilio for the SMS messages. The issue is that I am using Swift for my app, and they have no examples in swift currently. This is my code for sending the message:
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()
}
But whenever I try and run that function, I get this
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>
I know that my credentials are correct.....
Is there a better way of doing this? Does anyone have an example out there?
Matthew, as mentioned in the comments above/we do not recommend that you send SMS from the REST API via client side code for security reasons.
We suggest that you wrap your credentials and sending of the SMS in a backend app using one of the available helper libraries in the examples seen here:
https://www.twilio.com/docs/api/rest/sending-messages
A colleague of mine actually wrote a post to address this for the Android community and it looks like we should definitely do the same for Swift, which would be more my speed.
[Update]: How to send an SMS from Swift post.
Hope this helps.

Resources