add headers in api Swift / xcode - swift

I have to use an api link and the website said that I have to add my key in the header
but I don t know how to add it
I tried like this but is not working :(
can someone please help?
struct PollenRequest {
let resourceUrl: URL
let API_KEY = "123wrsgsdfhseraq24eewfesd"
init(location: String){
let resourceString = "https://api.ambeedata.com/latest/pollen/by-place?place=\(location)"
guard let resourceUrl = URL(string: resourceString) else { fatalError() }
let request = NSMutableURLRequest(url: NSURL(string: resourceString)! as URL)
request.addValue("123wrsgsdfhseraq24eewfesd",forHTTPHeaderField: "x-api-key")
self.resourceUrl = resourceUrl
}
func getPollen (completion: #escaping(Result<[PollenData], PollenError>) -> Void){
let dataTask = URLSession.shared.dataTask(with: resourceUrl){data, _, _ in
guard let jsonData = data else {
completion(.failure(.noData))
return
}
do{
let decoder = JSONDecoder()
let pollenResponse = try decoder.decode(PollenResponse.self, from: jsonData)
let pollenDetails = pollenResponse.data
completion(.success(pollenDetails))
}catch{
completion(.failure(.notProcessedData))
}
}
dataTask.resume()
}
}

Rather than saving the URL you have to save the URLRequest
And don't use NS.. types if there is a native Swift equivalent
struct PollenRequest {
let urlRequest: URLRequest
let API_KEY = "123wrsgsdfhseraq24eewfesd"
init(location: String) {
let resourceString = "https://api.ambeedata.com/latest/pollen/by-place?place=\(location)"
guard let resourceUrl = URL(string: resourceString) else { fatalError() }
var request = URLRequest(url: resourceUrl)
request.addValue(API_KEY, forHTTPHeaderField: "x-api-key")
request.addValue("application/json", forHTTPHeaderField: "Content-type")
self.urlRequest = request
}
func getPollen (completion: #escaping(Result<[PollenData], PollenError>) -> Void){
let dataTask = URLSession.shared.dataTask(with: urlRequest) {data, _, _ in
guard let jsonData = data else {
completion(.failure(.noData))
return
}
do{
let decoder = JSONDecoder()
let pollenResponse = try decoder.decode(PollenResponse.self, from: jsonData)
let pollenDetails = pollenResponse.data
completion(.success(pollenDetails))
}catch{
completion(.failure(.notProcessedData))
}
}
dataTask.resume()
}
}
Side note:
In case of an error returning .notProcessedData is meaningless. You should return the real DecodingError

Related

How to make an API call with Swift?

So I'm practising trying to make API calls with Swift. The code is as below:
struct Example: Codable {
let userID: String
let ID: String
let title: String
let completed: String
}
func getJson(completion: #escaping (Example)-> ()) {
let urlString = "https://jsonplaceholder.typicode.com/todos/1"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) {data, res, err in
if let data = data {
let decoder = JSONDecoder()
if let json: Example = try? decoder.decode(Example.self, from: data) {
completion(json)
}
}
}.resume()
}
}
getJson() { (json) in
print(json.ID)
}
However, I am unable to print out anything when getJson is called.
The example API I used is found here.
The tutorial that I used to help me write the code is found here.
Modified your variable name and data type exactly as your API response.
struct Example: Codable {
let userId: Int
let id: Int
let title: String
let completed: Bool
}
func getJson(completion: #escaping (Example)-> ()) {
let urlString = "https://jsonplaceholder.typicode.com/todos/1"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) {data, res, err in
if let data = data {
let decoder = JSONDecoder()
do {
let json: Example = try! decoder.decode(Example.self, from: data)
completion(json)
}catch let error {
print(error.localizedDescription)
}
}
}.resume()
}
}
getJson() { (json) in
print(json.id)
}
You can also use CodingKey and can change your response during the init period.
struct Example: Codable {
var userID: Int
var ID: Int
var title: String
var completed: Bool
enum CodingKeys: String, CodingKey {
case userID = "userId"
case ID = "id"
case title = "title"
case completed = "completed"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
userID = try values.decode(Int.self, forKey: .userID)
ID = try values.decode(Int.self, forKey: .ID)
title = try values.decode(String.self, forKey: .title)
completed = try values.decode(Bool.self, forKey: .completed)
title = "Title: \(title)"
}
}
func getJson(completion: #escaping (Example)-> ()) {
let urlString = "https://jsonplaceholder.typicode.com/todos/1"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) {data, res, err in
if let data = data {
do {
let json: Example = try JSONDecoder().decode(Example.self, from: data)
completion(json)
}catch let error {
print(error.localizedDescription)
}
}
}.resume()
}
}
getJson() { (json) in
print("ID: \(json.ID) \(json.title)")
}
import UIKit
class ApiManager: NSObject {
static func postApiRequest(url: String,parameters:[String: Any],completion: #escaping([String: Any])-> Void) {
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do{
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions())
let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")
}
if let data = data {
do{
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
print ("data = \(jsonResponse)")
}catch _ {
print ("OOps not good JSON formatted response")
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
}
}
}

URLSession.shared.dataTask block not running

I'm trying to make a request to an API. Without the completion handler, the request proceeds without issue. However, now that I've added in a completion handler, the URLSession.shared.dataTask block doesn't appear to run at all; the second print statement never prints. How should I adjust my code to fix this issue?
func makeRequestToApi(word: String, completionHandler: #escaping ([String]) -> Void) {
var array = [String]()
let appId = ""
let appKey = ""
let language = "en-us"
let unwrappedURL = URL(string: "https://od-api.oxforddictionaries.com:443/api/v2/entries/\(language)/\(word)")!
var request = URLRequest(url: unwrappedURL)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
print("THIS STATEMENT PRINTS...")
let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
print("AND THIS STATEMENT")
if let data = data,
let _ = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) {
do {
let root = try JSONDecoder().decode(Root.self, from: data)
let results = root.results
for result in results {
for lexical in result.lexicalEntries {
for entry in lexical.entries {
for sense in entry.senses {
for example in sense.examples {
array.append(example.text)
}
}
}
}
}
} catch {
print(error)
}
completionHandler(array)
}
}
dataTask.resume()
}
This is the function that I used on another view controller that returned data for the same words:
func makeRequestToApi() {
let appId = ""
let appKey = ""
let language = "en-us"
let strictMatch = "false"
var word = search
word = word.lowercased()
let oxDicURL = URL(string: "https://od-api.oxforddictionaries.com:443/api/v2/entries/\(language)/\(word)?strictMatch=\(strictMatch)")
if let unwrappedURL = oxDicURL {
var request = URLRequest(url: unwrappedURL)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let data = data,
let _ = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) {
do {
let root = try JSONDecoder().decode(Root.self, from: data)
let results = root.results
for result in results {
for lexical in result.lexicalEntries {
for entry in lexical.entries {
for sense in entry.senses {
for example in sense.examples {
print(example.text)
self.array.append(example.text)
}
}
}
}
}
self.search = word
DispatchQueue.main.async() {
self.performSegue(withIdentifier: "goToDetail", sender: nil)
}
} catch {
print(error)
}
}
}
dataTask.resume()
}
}

Swift - Multiple URL Request - Code To Refactor and To Reuse

I'm new to Swift and I am trying to refactor my URL Post requests. I have multiple URL POST requests inside the same View Controller like this. Everything works fine but it seems to me that there is a lot of repetitive code that could be reused. Particularly, I don't know how to pass/handle different Data Models that should be used in parseRequest1 and parseRequest2. I also read that there should be only one session used for URL requests within the same project. Any help would be greatly appreciate it!
func request1() {
let parameters = [...//some parameters to send]
guard let url = URL(string: "https//www.....") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let parametersToSend = try? JSONSerialization.data(withJSONObject: parameters, options: [])
else {
print("Error")
return
}
request.httpBody = parametersToSend
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let safeData = data {
self.parseRequest1(data: safeData)
}
}.resume()
}
func parseRequest1(data: Data){
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(DataModelForRequest1.self, from: data)
DispatchQueue.main.async {
self.performAction1(request1Result)
}
} catch {
print(error)
}
}
Then I have another URL request request2 which is almost identical except the parameters, and model to be used for decoding and action inside parseRequest2.
func request2() {
let parameters = [...//some parameters to send]
guard let url = URL(string: "https//www.....") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let parametersToSend = try? JSONSerialization.data(withJSONObject: parameters, options: [])
else {
print("Error")
return
}
request.httpBody = parametersToSend
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let safeData = data {
self.parseRequest2(data: safeData)
}
}.resume()
}
func parseRequest2(data: Data){
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(DataModelForRequest2.self, from: data)
DispatchQueue.main.async {
self.performAction2(request2Result)
}
} catch {
print(error)
}
}
The only differences seem to be:
request parameters
type of model returned
the action you do after the response is received
This means that we can write this as one single method taking the above three values as parameters:
func request<T: Codable>(modelType: T.Type, parameters: [String: Any], completion: (T) -> Void) {
func parseResponse(data: Data){
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(T.self, from: data)
DispatchQueue.main.async {
completion(decodedData)
}
} catch {
print(error)
}
}
guard let url = URL(string: "https//www.....") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let parametersToSend = try? JSONSerialization.data(withJSONObject: parameters, options: [])
else {
print("Error")
return
}
request.httpBody = parametersToSend
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let safeData = data {
parseResponse(data: safeData)
}
}.resume()
}
You can then call this method with the appropriate parameters as per your needs.

I am doing a post request where I want to type in a question and with the post request get the most common answer

I have done my Post-request but I am unsure about how to make it possible to send a full question and to get the most common answers back to my app.
I am in such a big need of this code in my program so would love to get some examples on how to make it work
Have tried to right the question into the parameters with a "+" instead of space which resulted into nothing.
#IBAction func GetAnswer(_ sender: Any) {
let myUrl = URL(string: "http://www.google.com/search?q=");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = questionAsked;
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
print("response = \(String(describing: response))")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let answer = parseJSON[" Answer "] as? String
self.AnswerView.text = ("Anwer: \(String(describing: answer))")
}
} catch {
print(error)
}
}
task.resume()
}
You do not use google.com/search, please check the api documentation
Paste following in Playground, should give a good start
struct Constants {
static let apiKey = "YOUR_API_KEY"
static let bundleId = "YOUR_IOS_APP_BUNDLE_ID"
static let searchEngineId = "YOUR_SEARCH_ENGINE_ID"
}
func googleSearch(term: String, callback:#escaping ([(title: String, url: String)]?) -> Void) {
let urlString = String(format: "https://www.googleapis.com/customsearch/v1?q=%#&cx=%#&key=%#", term, Constants.searchEngineId, Constants.apiKey)
let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
guard let url = URL(string: encodedUrl ?? urlString) else {
print("invalid url \(urlString)")
return
}
let request = NSMutableURLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
request.httpMethod = "GET"
request.setValue(Constants.bundleId, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
let session = URLSession.shared
let datatask = session.dataTask(with: request as URLRequest) { (data, response, error) in
guard
error == nil,
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any]
else {
// error handing here
callback(nil)
return
}
guard let items = json["items"] as? [[String : Any]], items.count > 0 else {
print("no results")
return
}
callback(items.map { ($0["title"] as! String, $0["formattedUrl"] as! String) })
}
datatask.resume()
}
Usage
googleSearch(term: "George Bush") { results in
print(results ?? [])
}
Create a new search engine using following url
https://cse.google.com/cse/create/new
If you would like search entire web, use following steps
edit your engine using https://cse.google.com/cse/setup/basic?cx=SEARCH_ENGINE_ID
remove any pages listed under Sites to search
turn on Search the entire web

urlrequest not sending post request

Hi i am new to IOS App developement.
My code is
func sendRequest<T: Decodable>(api: String, parameters: [String: String]? = nil, outputBlock: #escaping (T) -> () ) {
guard let url = URL(string: "http://xxyyzz.com/appRegister.php") else {return}
print("hitting : -", url.absoluteString)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let newparam = ["name": "rr", "pass": "123456", "email": "rr#rr.com", "passConfirm":"123456"]
let httpBody = try? JSONSerialization.data(withJSONObject: newparam)
request.httpBody = httpBody
if let data = request.httpBody, let str = String(data: data, encoding: String.Encoding.utf8) {
print(str)
}
URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
DispatchQueue.main.async {
Indicator.shared.hideProgressView()
if let err = error {
print(err.localizedDescription)
return
}
guard let data = data else {return}
do {
let obj = String(data: data, encoding: String.Encoding.utf8)
print(obj ?? "oberrrrr")
}
}
}.resume()
}
and console printed result as per code is below
hitting : - http://xxyyzz.com/appRegister.php
{"email":"rr#rr.com","passConfirm":"123456","name":"rr","pass":"123456"}
{"error":"Please enter all fields."}
url and parameters works well on postman that means their is something missing in my code.
just to answer the problem if anyone else faces this.
this code is fine but the problem was with php web-service as the backend developer was not accepting json values as parameter instead form data was need to send.
So, two types of fix can be made here
accept json at backend by adding :-
$postdata = file_get_contents("php://input");
$request = json_decode($postdata, true);
send form data instead json
func sendRequest<T: Decodable>(api: String, parameters: [String: Any]? = nil, outputBlock: #escaping (T) -> () ) {
guard let url = URL(string: api) else {return}
print("hitting : -", url.absoluteString)
var request = URLRequest(url: url)
if let parameters = parameters {
request.httpMethod = "POST"
var postArr = [String]()
for(key, value) in parameters
{
postArr.append(key + "=\(value)")
}
let postString = postArr.map { String($0) }.joined(separator: "&")
request.httpBody = postString.data(using: .utf8)
if let data = request.httpBody, let str = String(data: data, encoding: String.Encoding.utf8) {
print(str)
}
}
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
Indicator.shared.hideProgressView()
if let err = error {
print(err.localizedDescription)
return
}
guard let data = data else {return}
do {
let obj = try JSONDecoder().decode(T.self, from: data)
outputBlock(obj)
} catch let jsonErr {
print(jsonErr)
}
}
}.resume()
}