Skip to content

Instantly share code, notes, and snippets.

@amrangry
Created March 20, 2017 08:29
Show Gist options
  • Save amrangry/f47e5bec3cbd23623a9e9dff7295f75f to your computer and use it in GitHub Desktop.
Save amrangry/f47e5bec3cbd23623a9e9dff7295f75f to your computer and use it in GitHub Desktop.
this file is aiming to use URLSession to make a web service api call using swift 3
//
// DataTask.swift
//
//
// Created by Amr AlGhadban on 2/15/17.
// Copyright © 2017 Amr AlGhadban. All rights reserved.
//
import Foundation
class DataTask: NSObject {
class var sharedInstance : DataTask{
struct Static {
static let instance : DataTask = DataTask()
}
return Static.instance
}
private static func apiURlBuilder (_ subUrl : String?)-> String {
return ConstantsStruct.WebServiceAPIKey.BASEURL + subUrl!
}
// inoke via key=value & key=value
public static func invokeAPI(_ urlSubString: String, parameters: String?, completionHandler:@escaping (_ status: Bool, _ object: NSDictionary?) -> Void){
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let defaultConfigObject = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultConfigObject)
let url = URL(string: apiURlBuilder(urlSubString))
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = parameters?.data(using: String.Encoding.utf8)
urlRequest.timeoutInterval = 10
let task = defaultSession.dataTask(with: urlRequest, completionHandler: { data, response, error in
guard error == nil && data != nil else {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
completionHandler(false, nil)
DispatchQueue.main.async(execute: {
// self.showAlertWithTitle("TrucksGo", message: error?.localizedDescription)
})
return
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode == 200 {
do {
//Store response in NSDictionary for easy access
let responseObj = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! NSDictionary
print("*** parsed date as NSDictiornary : ",responseObj)
if let statusCode : Int = responseObj["responseCode"] as? Int , 200...299 ~= statusCode {
DispatchQueue.main.async {
completionHandler(true, responseObj as NSDictionary)
}
} else {
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
print(dataString ?? "No data")
DispatchQueue.main.async {
completionHandler(false, responseObj as NSDictionary)
}
}
} catch {
DispatchQueue.main.async {
completionHandler(false, nil)
}
}
} else {
DispatchQueue.main.async {
completionHandler(false, nil)
}
}
})
task.resume()
}
}
/*
func loadingJSON(_ link:String, postString:String, completionHandler: @escaping (_ JSONObject: AnyObject) -> ()) {
if(isConnectedToNetwork() == false){
completionHandler("-1" as AnyObject)
return
}
let request = NSMutableURLRequest(url: URL(string: link)!)
request.httpMethod = "POST"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
//JSON successfull
do {
let parseJSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
DispatchQueue.main.async(execute: {
completionHandler(parseJSON as AnyObject)
});
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
task.resume()
}
func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
So now you can easily call this in your app wherever you want
loadingJSON("yourDomain.com/login.php", postString:"email=\(userEmail!)&password=\(password!)") {
parseJSON in
if(String(describing: parseJSON) == "-1"){
print("No Internet")
} else {
if let loginSuccessfull = parseJSON["loginSuccessfull"] as? Bool {
//... do stuff
}
}
*/
@amrangry
Copy link
Author

how to use this file is by the following line for codes

           // TODO show loader 
            let params =  "mobile_no=01098558500&password=123123" 
            DataTask.invokeAPI("url/login", parameters: params, completionHandler: {(status: Bool,object: NSDictionary?) in
              // TODO close loader 
                 if (status == true){
          
                   // TODO business logic
                    
                }else{
                
                 // TODO show alert Message for error
                
                }
            })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment