Skip to content

Instantly share code, notes, and snippets.

@janeshsutharios
Last active November 6, 2020 08:01
Show Gist options
  • Save janeshsutharios/bb30cf5d81bb7051a7dc26a4b1e7e902 to your computer and use it in GitHub Desktop.
Save janeshsutharios/bb30cf5d81bb7051a7dc26a4b1e7e902 to your computer and use it in GitHub Desktop.
Webservice call
// MARK: - WelcomeElement
struct WelcomeElement: Codable {
let userID, id: Int
let title: String
let completed: Bool
enum CodingKeys: String, CodingKey {
case userID = "userId"
case id, title, completed
}
}
typealias Welcome = [WelcomeElement]
struct WebService {
static func fetchData(url: String,httpMethod: HttpMethod, parameters:[String:Any],completion:@escaping(_:Data)->Void) {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)//URLSession.shared
var request = URLRequest(url: URL(string:url)!)
request.httpMethod = httpMethod == .get ? "GET" : "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
if data != nil {
let json = try JSONSerialization.jsonObject(with: data!)
print(json)//let string = String(data: data, encoding: String.Encoding.utf8)
completion(data!)
}
} catch {
print(error)
}
completion(Data())
})
task.resume()
}
}
enum HttpMethod {
case get
case post
}
//MARK: Usage
//WebService.fetchData(url: url, httpMethod: .post, parameters: params) { (_) in
//}
// More Rich functionality as -
struct WebService {
// static var headers:[String:String] = ["Content-Type":"application/x-www-form-urlencoded","Authorization":"dsds","devcheck":"123456789"]
// static var baseURL = "https://URL/api/v3/"
// static var authorizationKey = "dsd"
// static var authorizationValue = "dsd"
static func fetchData(appendsUrl:String = "",
endPoint: EndPoint,
httpMethod: HttpMethod,
parameters:[String:Any],
isLoader:Bool = true,
completion:@escaping(_:Data)->Void) {
let url = URL(string:baseURL + endPoint.rawValue + appendsUrl)!
var request = URLRequest(url: URL(string:baseURL + endPoint.rawValue + appendsUrl)!)
let httpMethod = httpMethod == .get ? "GET" : "POST"
request = createRequestWithDictionaryParameters(url: url, httpMethod: httpMethod, parameters: parameters)
let headerFormatted = authorizationKey + ":" + authorizationValue
let authorizationDetails = String(format: headerFormatted).data(using: String.Encoding.utf8)!
let base64String = authorizationDetails.base64EncodedString()
let authString = "Basic \(base64String)"
let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.httpAdditionalHeaders = ["Authorization": authString]
let session = URLSession(configuration: sessionConfiguration)
session.dataTask(with: request) { (data, response, error) in
guard error == nil else {
DispatchQueue.main.async {
print(response?.description ?? "")
completion(Data())
}
return
}
guard let _ = data else {
DispatchQueue.main.async {
completion(Data())
}
return
}
do {
if data != nil {
let _ = try JSONSerialization.jsonObject(with: data!)
let string = String(data: data!, encoding: String.Encoding.utf8)
print("URL-->",baseURL + endPoint.rawValue + appendsUrl)
print("Parameters-->", parameters)
print("Response--", string ?? "")
DispatchQueue.main.async {
completion(data!)
}
}
} catch let err {
print("API parsing error -For \(baseURL + endPoint.rawValue + appendsUrl), Param \(parameters)--",err)
DispatchQueue.main.async {
completion(Data())
}
return
}
}.resume()
}
static func createRequestWithDictionaryParameters(url: URL, httpMethod: String, parameters: [String:Any]) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = httpMethod.uppercased()
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue( authorizationValue , forHTTPHeaderField: authorizationKey )
//request.setValue("11", forHTTPHeaderField: "11")//preProdSetting
if httpMethod == "POST" {
guard let jsonData = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else { return URLRequest(url: url) }
request.httpBody = jsonData
}
return request
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment