Trying to add email contacts to Sendgrid - ios

Problem: How can I add an email to a Sendgrid contact list in Swift?
Here's what I've done so far (this is not working)
var request = URLRequest(url: URL(string: sendGridURL)!)
request.httpMethod = "PUT"
let json = [
"listIds": ["a7aab3b0-0307-40e6-aa6f-7a3964b8fa1f", "0464f62d-9bb7-440c-8f64-ff2b66ec199b"],
"contacts": [[ "email" : "\(email)" ]]
];
//Headers
request.addValue("Bearer \(sendGridAPIKey)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do {
let data = try JSONSerialization.data(withJSONObject: json, options: [])
request.httpBody = data
} catch {
print("sendgrid \(error)")
}
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { print("sendgrid \(error!.localizedDescription)"); return }
guard let data = data else { print("sendgrid Empty data"); return }
if let str = String(data: data, encoding: .utf8) {
print("sendgrid \(str)")
}
}.resume()
}

The issue was I was using POST not PUT. Now, I'm having the issue where I cannot add contacts to a specific list.

Related

Making a url request session returns empty while postman returns data

I'm trying to make an API call here using a post method, however I keep getting
[[boringssl] boringssl_metrics_log_metric_block_invoke(144)]
and the data returned is an empty object {"finalResults":[]}.
Tested the API using postman and the data returns safely.
This is my code:
var dict = Dictionary<String, String>()
dict = [
"queryText": query,
"lat": "31.206865038834433",
"long": "29.965068562105422",
"pageToken": "",
]
let url:URL = URL(string: apiEndPointURLString)!
let session = URLSession.shared
var postData = NSData()
do{
postData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData
}catch {
print("error serializing.......\n\n\n\n")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length")
request.setValue("text/html", forHTTPHeaderField: "Content-Type")
request.setValue("json/application", forHTTPHeaderField: "Accept")
request.httpBody = postData as Data
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print(dataString ?? "no data")
}
task.resume()

How to Compress UIIMage Using TinyPNG Swift

I have a request in Swift 5 that is trying to make a call to tinify.com. It is supposed to give me back a URL to a compressed image. I am currently getting this error in the print field:
{"error":"Not found","message":"This endpoint does not exist."}
TinyPNG.com API Reference
Code:
let string = "https://api.tinify.com/shrink"
let url = NSURL(string: string)
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "GET"
request.addValue("fakeAPIKey1234", forHTTPHeaderField: "user api")
request.addValue("/dev/stdout", forHTTPHeaderField: "dump-header")
request.addValue("\(String(describing: self.jpegData(compressionQuality: 0.8)!))", forHTTPHeaderField: "data-binary")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
guard error == nil else { print(error!.localizedDescription); return }
guard let data = data else { print("Empty data"); return }
if let str = String(data: data, encoding: .utf8) {
print("Grab Image from this url: \(str)")
}
}
Note: fakeAPIKey1234 is not actually the string I'm using. Also I'm sure there is more wrong with my code than this little issue.

HTTP Post request with body receiving null values to server

I am using trying to post some data to server using Swift URLRequest with using following code.
var request = URLRequest(url: URL(string: Global.ip)!)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postString = "cmd=getFavorites" + "&ab={\"userId\":\"\(userId)\",\"favId\":\"\(favoriteId)\",\"favoriData\":\(panelData)}&token=\(token)"
let newPostString = postString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
request.httpBody = newPostString?.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
completion(false)
return;
}
let json = JSON(data)
completion(true)
}
task.resume()

Swift HTTP Post Request returns HTML of site instead of JSON response

I am trying to reach a site that should take the username and password given and return a JSON which contains information stating whether or not the login data provided was valid or not.
However, all I'm getting back is the site's HTML code instead of a response. I've tried the request with the same parameters on https://www.hurl.it/ and have gotten the correct response so that does not seem to be the issue.
I use the following code:
private func uploadToAPI(username: String, password: String) {
guard let url = URL(string: "http://api.foo.com/login.php"),
let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics),
let encodedPassword = password.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) else {
self.loginButton.isLoading = false
return
}
let httpBodyParameters = ["user": encodedUsername, "password": encodedPassword, "client": "ios", "version": "5"]
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: httpBodyParameters, options: JSONSerialization.WritingOptions.prettyPrinted)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response.mimeType) // Prints "text/html"
}
if let data = data {
print(try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)) // Prints nil
print(String(data: data, encoding: String.Encoding.utf8)) // Prints the site's HTML
}
}.resume()
}
I fail to see where the issue is. I've also tried not setting the HTTP headers but that makes no difference. Anyone got any ideas?
It seems like not setting the HTTP header fields and using a string literal instead of a Dictionary as HTTP body data did it for me.
For anyone interested this is the code that now receives the expected response:
guard let url = URL(string: "http://api.foo.com/login.php?"),
let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics),
let encodedPassword = password.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) else {
if let delegate = self.delegate {
delegate.viewModelDidRejectLogin(self)
}
return
}
let httpBodyString = "user=\(encodedUsername)&password=\(encodedPassword)&client=ios&version=5"
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = httpBodyString.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
print(error)
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String : AnyObject] {
self.readLoginResponse(json)
}
} catch {
print(error)
}
}.resume()

How to POST request in Swift

I have this API http://my-api.mydoctorfinder.com/
that will return a bool value depending on the email and password you have entered.
My problem is it will always return false despite using the correct email and password.
I was thinking that I might have not sent the right parameter since I created a dictionary containing the email and password. Then passed it on NSJSONSerialization.dataWithJSONObject method
By the way, I was using SwiftyJson.
This is my code
//creates a dictionary and calls the PostRequest method
func attemptLogIn( email: String, password: String) {
let route = loggerURL
let body: [String:String] = ["email":email, "password":password]
makeHTTPPostRequest(route, body: body)
}
//performs post request
private func makeHTTPPostRequest(path: String, body: [String: AnyObject]) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted)
request.HTTPBody = jsonBody
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
//onCompletion(json, nil)
print("The Response: ")
print(json)
} else {
//onCompletion(nil, error)
print("The Response: ")
print("Hello")
}
})
task.resume()
} catch {
// Create your personal error
//onCompletion(nil, nil)
}
}
The response is simply a true or false i.e. its not a json object.
So i would suggest don't use Swifty son instead use Alamofire.
Following code should work for you:-
let myParameters = [
"email": "your email id",
"password": "your password"]
Alamofire.request(.POST, "http://my-api.mydoctorfinder.com/ ", parameters: myParameters)
.response { request, response, data, error in
print(request)
print(response)
if(response == true)
{
// do your thing
}
print(error)
}
Note: There might be a need to typecast response to bool
Also following is the screenshot of the link you gave, it returns true(and not a json object) [After registration, i tried to login with same credentials]
Try to create JSON object using NSJSONSerialization in this way:
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])
I assume that problem is in .PrettyPrinted constant.
Edit:
Also try adding correct content-type:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Here is the swift post request to get data :
func retriveTextDataByPost(requestURL:String, params: NSDictionary, handler:((dict:NSDictionary?) -> Void)) {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let url = NSURL(string: requestURL)
let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
do {
let postData = try NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted)
request.HTTPBody = postData
let postDataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if data != nil {
do {
let dictResult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
handler(dict: dictResult)
} catch { }
}
}
postDataTask.resume()
} catch { }
}
Check your keys for email and password with required input for APIs
Check your login URL

Resources