How to call api using URLSession in swift 5
Step 1 : Create New swift file link :("WebServiceManager.swift")
Step 2: Copy and paste this code in you
Step 2: Copy and paste this code in you
//
// WebServiceManager.swift
//
import Foundation
import UIKit
typealias ServiceResponse = (_ reponse:[String : AnyObject], _ error: Error?) -> Void
class WebServiceManager: NSObject, NVActivityIndicatorViewable
{
static let sharedInstance = WebServiceManager()
var reachability : Reachability?
var activity: NVActivityIndicatorView!
let baseURL = SERVER_URL
func checkConnection() -> Bool
{
self.reachability = Reachability(hostname: baseURL)
return (reachability?.isReachable)!
}
func makeHTTPGetRequest(path: String, onCompletion: @escaping ServiceResponse)
{
if checkConnection() == false
{
let viewController = APPLICATION_DELEGATE.navigationController.topViewController
if (viewController?.isKind(of: NoInternetViewController.self))!
{
return
}
else
{
setCenterViewController(strViewController: "NoInternetViewController", strStoryBoard: "NetworkStoryboard")
return
}
}
let stringURL = baseURL + path
var request = URLRequest(url: NSURL(string: stringURL)! as URL)
print("reqURL: \(stringURL)")
request.httpMethod = "GET"
if UserDefaults.standard.value(forKey: login_user_user_id) != nil && UserDefaults.standard.value(forKey: login_user_Authorizations) != nil
{
request.addValue("header value", forHTTPHeaderField: "header Key")
}
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print("reqResponse: \(json)")
onCompletion(json as! [String : AnyObject], error)
}
catch
{
onCompletion(["status" : false as AnyObject, "message" : "Failed to parse json" as AnyObject], error)
print("Failed to load: \(error.localizedDescription)")
}
})
task.resume()
}
func
makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: @escaping ServiceResponse)
{
if checkConnection() == false
{
let viewController = APPLICATION_DELEGATE.navigationController.topViewController
if (viewController?.isKind(of: NoInternetViewController.self))!
{
return
}
else
{
setCenterViewController(strViewController: "NoInternetViewController", strStoryBoard: "NetworkStoryboard")
return
}
}
let stringURL = baseURL + path
var request = URLRequest(url: NSURL(string: stringURL)! as URL)
print("reqURL: \(stringURL)")
print("reqObject:\(body)")
var jsonString: String = ""
jsonString = convertDictToString(dict: body)
print("json Object:\(jsonString)")
request.httpMethod = "POST"
request.timeoutInterval = 60
if UserDefaults.standard.value(forKey: login_user_user_id) != nil && UserDefaults.standard.value(forKey: login_user_Authorizations) != nil
{
request.addValue("header value", forHTTPHeaderField: "header Key")
}
request.httpBody = jsonString.data(using: .utf8)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
DispatchQueue.main.sync
{
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
do
{
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
print("reqResponse:\(json)")
onCompletion(json as! [String : AnyObject], error)
}
catch
{
onCompletion(["status" : false as AnyObject, "message" : "Failed to parse json" as AnyObject], error)
print("Failed to load: \(error.localizedDescription)")
}
}
})
task.resume()
}
func convertDictToString(dict :[String:AnyObject]) -> String
{
var finalString = ""
for (key, value) in dict
{
if let str = value as? String
{
finalString = finalString + key + "=" + str.addingPercentEncodingForQueryParameter()!
}
else if let arr = value as?[AnyObject]
{
let data = try! JSONSerialization.data(withJSONObject: arr, options: .prettyPrinted)
finalString = finalString + key + "=" + String(data: data, encoding: String.Encoding.utf8)!
}
else
{
let data = try! JSONSerialization.data(withJSONObject: value as! [String : AnyObject], options: .prettyPrinted)
finalString = finalString + key + "=" + String(data: data, encoding: String.Encoding.utf8)!
// finalString = finalString + key + "=" + convertDictToString(dict: value as! [String : AnyObject])
}
finalString = finalString + "&"
}
finalString.removeLast()
return finalString
}
func UploadImage(path: String,parameters: Dictionary<String,AnyObject>?,filename:String,image:UIImage, onCompletion:@escaping ServiceResponse)
{
let BOUNDARY:String = "AaB03x"
let strFilename = "\(String(describing: UserDefaults.standard.value(forKey: "user_id"))).jpeg" as AnyObject as! String
let stringURL = baseURL + path
print("reqURL:\(stringURL)")
print("reqObject:\(String(describing: parameters))")
let url = NSURL(string: stringURL)!
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 10)
let MPboundary:String = "--\(BOUNDARY)"
let endMPboundary:String = "\(MPboundary)--"
//convert UIImage to NSData
let data = image.jpegData(compressionQuality: 0.01)
let body:NSMutableString = NSMutableString();
if parameters != nil
{
for (key, value) in parameters!
{
body.appendFormat("\(MPboundary)\r\n" as NSString)
body.appendFormat("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n" as NSString)
body.appendFormat("\(value)\r\n" as NSString)
}
}
// set upload image, name is the key of image
body.appendFormat("%@\r\n",MPboundary)
body.appendFormat("Content-Disposition: form-data; name=\"\(filename)\"; filename=\"\(strFilename)\"\r\n" as NSString)
body.appendFormat("Content-Type: image/jpeg\r\n\r\n")
let end:String = "\r\n\(endMPboundary)"
let myRequestData:NSMutableData = NSMutableData();
myRequestData.append(body.data(using: String.Encoding.utf8.rawValue)!)
myRequestData.append(data!)
myRequestData.append(end.data(using: String.Encoding.utf8)!)
let content:String = "multipart/form-data; boundary=\(BOUNDARY)"
request.setValue(content, forHTTPHeaderField: "Content-Type")
request.setValue("\(myRequestData.length)", forHTTPHeaderField: "Content-Length")
request.httpBody = myRequestData as Data
request.httpMethod = "POST"
if UserDefaults.standard.value(forKey: login_user_user_id) != nil && UserDefaults.standard.value(forKey: login_user_Authorizations) != nil
{
request.addValue("header value", forHTTPHeaderField: "header Key")
}
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler:
{
data, response, error in
DispatchQueue.main.sync
{
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
do
{
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
print("reqResponse:\(json)")
onCompletion(json as! [String : AnyObject], error)
}
catch
{
onCompletion(["status" : false as AnyObject, "message" : "Failed to parse json" as AnyObject], error)
print("Failed to load: \(error.localizedDescription)")
}
}
})
task.resume()
}
}
Nice
ReplyDelete