I am trying to send Email using MailGun api with Swift. I created and activate free account with mailgun. Installed pod.
cocoapods mailgun pod
If I press button I am getting message "Email was sent" but I am not receiving this email, nor it is displays in mailgun "Logs" or "Reporting".
I have also added and verified my personal e-mail to "Authorized Recipients"
I tied to run on IOS simulator and actual devices no luck.
#IBAction func dddd(_ sender: Any) {
let mailgun = MailgunAPI(apiKey: "key-<my_key from mailgun>, clientDomain: "sandboxe437***********.mailgun.org")
mailgun.sendEmail(to: "me#mail.com", from: "Test User <myemail#mail.com", subject: "This is a test15", bodyHTML: "<b>test<b>") { mailgunResult in
if mailgunResult.success{
print("Email was sent")
}else{
print("error")
}
}
Any word of advise what did I missed?
Thank you,
Stalker
#Stalker, your from parameter does not have a closing >. I hope you have seen it.
If you are already using Alamofire for your network requests then no need for this extra dependency mailgun pod:
Swift 3.2
import Alamofire
let parameters = [
"from": "sender#whatyouwant.com",
"to": "anyRecipient#example.com",
"subject": "Subject of the email",
"text": "This is the body of the email."]
let header = [
"Authorization": "Basic YOUR-BASE64ENCODED-KEY",
"Content-Type" : "application/x-www-form-urlencoded"]
let url = "https://api.mailgun.net/v3/YOUR-DOMAIN/messages"
Alamofire.request(url,
method: .post,
parameters: parameters,
encoding: URLEncoding.default,
headers: header)
.responseJSON { response in
print("Response: \(response)")
}
In the header, you have to replace YOUR-BASE64ENCODED-KEY with the base64 encoded string of "API:YOUR-SECRET-API-KEY" where YOUR-SECRET-API-KEYis found on your Mailgun dashboard.
In the URL you also replace YOUR-DOMAIN with your Mailgun domain.
With that you should be good to go and send emails through Mailgun.
Related
I am trying to send a simple push notification with APNs. Going through the Apple Docs, I'm still a bit unsure if I am formulated my POST request correctly. Can someone verify if it's correct or if something needs to be fixed?
Note1: I am using certificate-based authentication (or at least I think I am).
Note2: apnsToken is the device token returned from application(didRegisterForRemoteNotificationsWithDeviceToken: ) (converted to a String based on #ytrewq's comment).
func sendNotification(apnsToken: String, title: String, body: String) {
let params: Parameters = [
"aps" : [
"alert" : [
"title" : title,
"body" : body
]
]
]
let headers: HTTPHeaders = [
":path": "/3/device/\(apnsToken)",
"apns-push-type": "alert"
]
AF.request("https://api.push.apple.com", method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).response { response in
debugPrint(response)
}
}
Running the code above gives me the error failure(Alamofire.AFError.sessionTaskFailed(error: Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response".
I have an app and now I want to store some data in google sheet using google sheet apis. I don't have google sign in in the app and I enabled api in developer console.
I checked other answers on stackoverflow but they are using google sign in to get access token.
Here is my code,
func writeGoogleSheet() {
let sheetID = "GoogleSheet ID"
let range = "A3:B4"
let requestParams = [
"values": [
["hi1", "hi2"],
["hi3", "hi4"]
]
]
let requestURL = "https://sheets.googleapis.com/v4/spreadsheets/\(sheetID)/values/\(range)?valueInputOption=USER_ENTERED&key=API_Key"
let req = AF.request(requestURL, method: .put, parameters: requestParams, encoding: JSONEncoding.default, headers: nil)
req.responseJSON { response in debugPrint(response) }
}
[Response Body]:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
So please guide me how to implement this without google sign in? I have one google sheet where I want to write data.
Thanks in advance.
I test this thing many time in many devices with different ios versions but always succeeded to make API call. Also test with testflight build and got success for same request params.
Only at the time of App store review I got the error "JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."
for a correct formatted "requestParameter": {"device_token": "cBXIAfxpEpk:APA91bH8AZYHqMniP5oGNuHT7czD-wHm_ioE-th1_LkN3_w5w_KUa5grT6Ff73D8j9Kn-xONeK4ytT8ZSfVssG9mf4KwJzhY7WdoSxUHxLKNxyGMI0g9ieyuyF25Pi3KwFXDIQmawmow", "time_zone": "America/Los_Angeles", "device_type": "ios", "username": "demo", "password": "password", "location": "37.452728,-121.940140"}
these are the information i got from firebase files
I am sure its not for response because I also verified with backend but there is no log fired at that time , So its unable to make request from mobile side.
here is my API method
func serviceCall(withPath path:String, withData param:[String:Any], withCompletionHandler completion:#escaping (AnyObject?) -> Void){
let requestURL = String(format: "%#%#", BaseURL, path)
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 40
manager.request(requestURL, method: .post, parameters: param, encoding: URLEncoding.methodDependent, headers: nil).responseJSON { (responseJson) in
print("Response 10: \(responseJson)")
if ((responseJson.result.value != nil)){
// store details to firebase
} else {
// store details to firebase
}
}
}
please help me out already rejected by app store for many times :(
Thank you in advance !!
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.
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)
}