Skip to content

Instantly share code, notes, and snippets.

@Nazmul56
Created April 26, 2020 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nazmul56/1156db86091553abab88254c23ef189e to your computer and use it in GitHub Desktop.
Save Nazmul56/1156db86091553abab88254c23ef189e to your computer and use it in GitHub Desktop.
Swift api manager
/
// APIManager.swift
// iOSDuComm
//
// Created by Sufian on 20/6/19.
// Copyright © 2019 Abu Sufian. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import MBProgressHUD
class APIManager: NSObject {
static let shared = APIManager()
override init() {
super.init()
}
//MARK:- Login Methods
func enterWithUsername( name: String, success: @escaping () -> Void) {
let parameter = ["username" : name]
Alamofire.request(Router.enter.path, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: nil).responseJSON {
(response: DataResponse<Any>) in
print("API: \(Router.profile.path), result: \(String(describing: response.result.value))")
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200) {
guard let swiftyJsonVar = JSON(response.result.value as Any).dictionaryObject, let data = swiftyJsonVar["data"] as? [String : Any], let ok = data["smsSent"] as? Bool else {
return
}
if ok {
success()
}
} else {
self.showErrorFor(statusCode)
Utility.removeLoading()
}
break
case .failure(let error):
Utility.removeLoading()
Utility.showAlert("Error!!!", message: error.localizedDescription)
}
}
}
func verifyOTP( pin: String, For phoneNumber: String,serverResponse: @escaping (( cookie: HTTPCookie, userName: String, sipData: [String : Any]) -> Void)) {
let parameter = ["token" : pin]
Alamofire.request(Router.verifyOTP(phone: phoneNumber).path, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: nil).responseJSON {
(response: DataResponse<Any>) in
print("API: \(Router.profile.path), result: \(String(describing: response.result.value))")
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200) {
guard let swiftyJsonVar = JSON(response.result.value as Any).dictionaryObject, let data = swiftyJsonVar["data"] as? [String : Any], let sipData = data["sipData"] as? [String : Any] else {
return
}
print(data)
if let
headerFields = response.response?.allHeaderFields as? [String: String],
let URL = response.request?.url
{
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: URL)
let cookie = cookies.first!
serverResponse(cookie, phoneNumber, sipData)
}
} else {
self.showErrorFor(statusCode)
}
break
case .failure(let error):
print(error)
}
}
}
func loginWithPassword( number: String, password: String, serverResponse: (( cookie: HTTPCookie, userName: String) -> Void)?, onFail: (( error: String) -> Void)?) {
let values = ["username" : number, "password" : password]
let url = URL(string: Router.loginWithPassword.path)!
var request = URLRequest(url: url)
// request.allHTTPHeaderFields = header
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.responseJSON { response in
print("request body: \(String(describing: response.request?.httpBody))")
print("API: \(Router.profile.path), result: \(String(describing: response.result.value))")
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200){
guard let swiftyJsonVar = JSON(response.result.value as Any).dictionaryObject, let _ = swiftyJsonVar["data"] as? [String : AnyObject] else {
return
}
if let
headerFields = response.response?.allHeaderFields as? [String: String],
let URL = response.request?.url
{
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: URL)
let cookie = cookies.first!
serverResponse?(cookie, number)
}
} else {
onFail?("Status code \(statusCode)")
}
break
case .failure(let error):
print(error)
}
}
}
// Enter into app via FB authentication
func enter(authCode: String, serverResponse: @escaping (( cookie: HTTPCookie, userName: String) -> Void)) {
DataManager.shared.deleteCookies()
let url = URL(string: Router.enter.path)!
var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = ["fbAuthorizationCode" : authCode]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.responseJSON { response in
print("request body: \(String(describing: response.request?.httpBody))")
print("API: \(Router.profile.path), result: \(String(describing: response.result.value))")
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200){
guard let swiftyJsonVar = JSON(response.result.value as Any).dictionaryObject, let jsonData = swiftyJsonVar["data"] as? [String : AnyObject], let username = jsonData["username"] as? String else {
return
}
if let
headerFields = response.response?.allHeaderFields as? [String: String],
let URL = response.request?.url
{
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: URL)
let cookie = cookies.first!
serverResponse(cookie, username)
}
} else {
self.showErrorFor(statusCode)
}
break
case .failure(let error):
print(error)
}
}
}
//User Login status checking
func isLogedin(_response: @escaping ((_ isLogedin: Bool) -> Void)) {
callAPI(Router.isLoggedIn.path, method: .get, parameters: nil, encoding: URLEncoding.default, onSuccess: { (swiftyJsonVar) in
let data = swiftyJsonVar["data"] as! [String : Any]
let loggedin = data["loggedIn"] as! Bool
_response(loggedin)
}, onFail: { _ in
_response(false)
})
}
func sendDeviceTokenToServer() {
guard let token = DataManager.shared.getDeviceToken() else {
return
}
var parameters = [String : Any]()
parameters = ["pushToken" : token, "tokenType" : "apn"]
callAPI(Router.pushToken.path, method: .post, parameters: parameters, encoding: JSONEncoding.default, onSuccess: nil, onFail: nil)
}
//MARK:- File Uploading Methods
func getSignedURL(ForMimeType mime: String, success: @escaping (_ data: [String : Any]) -> Void) {
let parameters = ["mimeType" : mime]
callAPI(Router.fileUploadSignedURL.path, method: .get, parameters: parameters, encoding: URLEncoding.default, onSuccess: { (swiftyJsonVar) in
guard let data = swiftyJsonVar["data"] as? [String : Any] else {
return
}
success(data)
}, onFail: nil)
}
func uploadFile(endUrl: String, data: Data, mimeType: String, success: @escaping (() -> Void)){
let headers = [
/ "Authorization": "your_access_token", in case you need authorization header /
"Content-type": mimeType,
]
var putRequest = URLRequest(url: URL(string: endUrl)!)
putRequest.httpBody = data
putRequest.allHTTPHeaderFields = headers
putRequest.httpMethod = HTTPMethod.put.rawValue
let uploadSession = URLSession.shared
let executePostRequest = uploadSession.dataTask(with: putRequest as URLRequest) { (data, response, error) -> Void in
if let response = response as? HTTPURLResponse
{
print(response.statusCode)
success()
}
if let data = data
{
let json = String(data: data, encoding: String.Encoding.utf8)
print("Response data: \(String(describing: json))")
}
}
executePostRequest.resume()
}
// Logout Methods
func logout() {
callAPI(LOGOUT, method: .get, parameters: nil, encoding: URLEncoding.default, onSuccess: nil, onFail: nil)
}
//MARK:- General Method
func callAPI( url: String, method: HTTPMethod, parameters: [String : Any]?, encoding: ParameterEncoding, onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
guard let header = getHeader() else {
onFail?("")
return
}
Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: header).responseJSON {
(response: DataResponse<Any>) in
print("API: \(Router.profile.path), result: \(String(describing: response.result.value))")
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200){
guard let swiftyJsonVar = JSON(response.result.value as Any).dictionaryObject else {
return
}
onSuccess?(swiftyJsonVar)
} else {
self.showErrorFor(statusCode)
}
break
case .failure(let error):
onFail?(error.localizedDescription)
print(error)
}
}
}
func callAPI2( url: String, parameters: [String : Any], method: HTTPMethod, onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
guard var header = getHeader() else {
return
}
header ["Content-Type"] = "application/x-www-form-urlencoded"
header ["x-version"] = "\(APP_VERSION)"
header ["x-platform"] = "iOS"
Alamofire.request(url, method: method, parameters: parameters, encoding: URLEncoding.httpBody, headers: header).responseJSON {
(response: DataResponse<Any>) in
print("API: \(url), result: \(String(describing: response.result.value))")
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200){
guard let swiftyJsonVar = JSON(response.result.value as Any).dictionaryObject, let data = swiftyJsonVar["data"] as? [String : Any] else {
return
}
onSuccess?(data)
} else {
self.showErrorFor(statusCode)
}
break
case .failure(let error):
onFail?(error.localizedDescription)
}
}
}
func callAPI3( url: String, parameters: [String : Any], method: HTTPMethod, onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
guard var header = getHeader() else {
return
}
header["Content-Type"] = "application/x-www-form-urlencoded"
Alamofire.request(url, method: method, parameters: parameters, encoding: URLEncoding.httpBody, headers: header).responseJSON {
(response: DataResponse<Any>) in
print("API: \(url), result: \(String(describing: response.result.value))")
let bKashTrxnResponse = JSON(response.result.value as Any)["data"]
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200){
Utility.removeLoading()
Utility.showAlert("Recharge Successful", message: "Your \(APP_NAME) account has been recharged successfully" )
} else {
self.showErrorFor(statusCode)
Utility.removeLoading()
print(statusCode)
let errorMessage = JSON(response.result.value as Any).dictionaryObject?["message"]
if let message = errorMessage {
onFail?(message as! String)
}
else {
onFail?("Unknown error occurred")
}
}
break
case .failure(let error):
onFail?(error.localizedDescription)
}
}
}
func callAPIForPostingDataWithBody( url: String, data: Data?, method: HTTPMethod, onSuccess: (( data: [String : Any]) -> Void)?, onFail: (( error: String) -> Void)?) {
guard let header = getHeader() else {
onFail?("Cookie not found")
return
}
let url = URL(string: _url)!
var request = URLRequest(url: url)
request.allHTTPHeaderFields = header
request.httpMethod = method.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = data
Alamofire.request(request)
.responseJSON { response in
print("request body: \(String(describing: response.request?.httpBody))")
print("API: \(url), result: \(String(describing: response.result.value))")
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200){
guard let swiftyJsonVar = JSON(response.result.value as Any).dictionaryObject, let data = swiftyJsonVar["data"] as? [String : AnyObject] else {
return
}
onSuccess?(data)
} else {
onFail?("Status code \(statusCode)")
}
break
case .failure(let error):
print(error)
}
}
}
//MARK:- Message Threads
func getMessageThreads( onSuccess: @escaping (( threads: [ [String : AnyObject] ], _ users: [String : Any]) -> Void)) {
callAPI(Router.messageThreads(username: DataManager.shared.getCurrentUserNumber()).path, method: .get, parameters: nil, encoding: URLEncoding.default, onSuccess: { (swiftyJsonVar) in
guard let data = swiftyJsonVar["data"] as? [String : AnyObject], let threads = data["threads"] as? [[String : AnyObject]], let users = data["users"] as? [String : Any] else {
return
}
onSuccess(threads, users)
}, onFail: nil)
}
func getMessageThread( threadId: String, onSuccess: @escaping ((_ thread: [String : Any]) -> Void)) {
callAPI(Router.messsageThread(threadId: threadId).path, method: .get, parameters: nil, encoding: URLEncoding.default, onSuccess: { (swiftyJsonVar) in
guard let data = swiftyJsonVar["data"] as? [String : Any], let thread = data["thread"] as? [String : Any] else {
return
}
onSuccess(thread)
}, onFail: nil)
}
func editMessage( message: ChatMessage, onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
updateMessage(message, method: .patch, onSuccess: onSuccess, onFail: onFail)
}
func deleteMessage( message: ChatMessage, onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
updateMessage(message, method: .delete, onSuccess: onSuccess, onFail: onFail)
}
private func updateMessage( message: ChatMessage, method: HTTPMethod, onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
guard let header = getHeader() else {
onFail?("Cookie not found")
return
}
let url = URL(string: Router.editMessage(message: message).path)!
var request = URLRequest(url: url)
request.allHTTPHeaderFields = header
request.httpMethod = method.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if method == .patch {
let values = ["newContent" : message.getMessageContent()]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
}
Alamofire.request(request)
.responseJSON { response in
print("request body: \(String(describing: response.request?.httpBody))")
print("API: \(url), result: \(String(describing: response.result.value))")
switch response.result {
case .success:
let statusCode: Int = (response.response?.statusCode)!
if (statusCode == 200){
guard let swiftyJsonVar = JSON(response.result.value as Any).dictionaryObject, let data = swiftyJsonVar["data"] as? [String : AnyObject] else {
return
}
onSuccess?(data)
} else {
onFail?("Status code \(statusCode)")
}
break
case .failure(let error):
print(error)
}
}
}
//MARK:- Group Methoods
func createGroup( members: [String], onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
var groupMembers = [String]()
groupMembers.insert("You", at: groupMembers.startIndex)
for i in 0..<members.count{
let contactName = Contact.manager.getNameFrom(members[i])
if let contactName = contactName {
groupMembers.append(contactName)
}
}
let groupMember = groupMembers.joined(separator: ", ")
var groupName = ""
if members.count > 4{
groupName = ("\(groupMembers[0]), \(groupMembers[1]), \(groupMembers[2]) And \(groupMembers.count - 3) others")
} else if members.count > 3{
groupName = ("\(groupMembers[0]), \(groupMembers[1]), \(groupMembers[2]) And \(groupMembers.count - 3) other")
}else{
groupName = groupMember
}
let parameters = ["users" : members, "name" : groupName] as [String : Any]
let value = try! JSONSerialization.data(withJSONObject: parameters)
callAPIForPostingDataWithBody(Router.group.path, data: value, method: .post, onSuccess: onSuccess, onFail: onFail)
}
func updateGroup( threadId: String, parameters: [String : Any], onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
let value = try! JSONSerialization.data(withJSONObject: parameters)
callAPIForPostingDataWithBody(Router.groupUpdate(id: threadId).path, data: value, method: .patch, onSuccess: onSuccess, onFail: onFail)
}
func addToGroup( threadId: String, users: [String], onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
let parm = ["users" : users]
let value = try! JSONSerialization.data(withJSONObject: parm)
callAPIForPostingDataWithBody(Router.addRemoveFromGroup(id: threadId, user: nil).path, data: value, method: .post, onSuccess: onSuccess, onFail: onFail)
}
func removeFromGroup( threadId: String, user: String, onSuccess: (( data: [String : Any]) -> Void)?, onFail: ((_ error: String) -> Void)?) {
callAPIForPostingDataWithBody(Router.addRemoveFromGroup(id: threadId, user: user).path, data: nil, method: .delete, onSuccess: onSuccess, onFail: onFail)
}
func getGroupMessageThreads( onSuccess: @escaping (( threads: [ [String : AnyObject] ]) -> Void)) {
let parameters = ["filter" : "group"]
callAPI(Router.messageThreads(username: DataManager.shared.getCurrentUserNumber()).path, method: .get, parameters: parameters, encoding: URLEncoding.default, onSuccess: { (swiftyJsonVar) in
guard let data = swiftyJsonVar["data"] as? [String : AnyObject], let threads = data["threads"] as? [[String : AnyObject]] else {
return
}
onSuccess(threads)
}, onFail: nil)
}
func getMessagesFor(threadId: String, beforeTime: Int?, afterTime: Int?, sequenceId: Int?, sender: String?, messageCount: Int, onSuccess: @escaping (( messages: [ [String : AnyObject] ], seenTime: [String : Any]) -> Void)) {
var parameters = [String : String]()
if let beforeTime = beforeTime {
parameters["before"] = "\(beforeTime):\(sender!):\(sequenceId!)"
}
if let afterTime = afterTime {
parameters["after"] = "\(afterTime):\(sender!):\(sequenceId!)"
}
parameters["limit"] = "\(messageCount)"
callAPI(Router.singleMessageThread(threadId: threadId).path, method: .get, parameters: parameters, encoding: URLEncoding.default, onSuccess: { (swiftyJsonVar) in
guard let data = swiftyJsonVar["data"] as? [String : AnyObject], let messages = data["messages"] as? Array<[String : AnyObject]>, let seenTime = data["seenTime"] as? [String : Any] else {
return
}
onSuccess(messages, seenTime)
}, onFail: nil)
}
func postContacts(_ contacts: [String], onSuccess: @escaping (() -> Void), onfail: @escaping (() -> Void)) {
if contacts.count == 0 {
onSuccess()
return
}
var parameters = [String : Any]()
parameters = ["contacts" : contacts]
callAPI(Router.postContacts(myPhoneNumber: Utility.getFormatedPhoneNumber(DataManager.shared.getCurrentUserNumber())).path, method: .post, parameters: parameters, encoding: JSONEncoding.default, onSuccess: { (_) in
onSuccess()
}, onFail: { error in
onfail()
})
}
func getRegisterdContacts(onSuccess: @escaping ((_ registeredContacts: [String : Any]) -> Void)) {
callAPI(Router.getContacts(myPhoneNumber: Utility.getFormatedPhoneNumber(DataManager.shared.getCurrentUserNumber())).path, method: .get, parameters: nil, encoding: URLEncoding.default, onSuccess: { (swiftyJsonVar) in
guard let data = swiftyJsonVar["data"] as? [String : Any] else {
return
}
onSuccess(data)
}, onFail: nil)
}
func getThreadId( mynumber: String, otherNumber: String, onSuccess: @escaping (( data: [String : Any]) -> Void)) {
if mynumber == otherNumber {
return
}
callAPI(Router.getThreadId(myNumber: mynumber, otherNumber: otherNumber).path, method: .get, parameters: nil, encoding: URLEncoding.default, onSuccess: { (swiftyJsonVar) in
guard let data = swiftyJsonVar["data"] as? [String : Any] else {
return
}
onSuccess(data)
}, onFail: nil)
}
func getProfile( onSuccess: @escaping (( data: [String : Any]) -> Void)) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment