Skip to content

Instantly share code, notes, and snippets.

@anandabayu
Last active February 22, 2020 18:21
Show Gist options
  • Save anandabayu/9989fe626ac853a792d49be8672e72de to your computer and use it in GitHub Desktop.
Save anandabayu/9989fe626ac853a792d49be8672e72de to your computer and use it in GitHub Desktop.
import Foundation
import Alamofire
class NetworkingClient {
typealias WebServiceResponse = (Data?, Error?) -> Void
typealias WebServiceResponsePost = (Data?, postError?, String?) -> Void
func get(_ url: URL, _ headers: HTTPHeaders, completion: @escaping WebServiceResponse){
AF.request(url, headers: headers).validate().responseJSON { response in
if let error = response.error {
let code = error.asAFError?.responseCode
if code == 401 {
return Switcher.sessionExpired()
}
completion(nil, error)
}else if let jsonArray = response.data {
completion(jsonArray, nil)
}
}
}
func post(_ url: URL, _ params: [String: Any], _ headers: HTTPHeaders, completion: @escaping WebServiceResponsePost){
AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { response in
if let error = response.error {
let code = response.response?.statusCode
if code == 401 {
return Switcher.sessionExpired()
}
if code == 400 {
if let responseData = response.data {
let jsonDecoder = JSONDecoder()
do {
let res = try jsonDecoder.decode(postError.self, from: responseData)
completion(nil, res, nil)
}catch let error{
completion(nil, nil, error.localizedDescription)
}
} else {
completion(nil, nil, error.localizedDescription)
}
}else if code == 500 {
completion(nil, nil, "500: Server error")
}else {
completion(nil, nil, error.localizedDescription)
}
}else if let jsonArray = response.data {
completion(jsonArray, nil, nil)
}
}
}
}
import UIKit
import SkyFloatingLabelTextField
import WebKit
import SSSpinnerButton
import SDWebImage
import LanguageManager_iOS
import Alamofire
enum TaskDefault: String {
case notifCustom = "task_notif_custome"
case notifTop = "task_notif_top"
case notifBot = "task_notif_bot"
case taskStart = "task_start_day"
case taskEnd = "task_end_day"
}
class TaskController: UIViewController {
/// CLIENTS
private let networkingClient = NetworkingClient()
private let token = UserDefaults.standard.string(forKey: "token")
let lang = LanguageManager.shared.currentLanguage.rawValue
/// Title
@IBOutlet weak var titleTextField: SkyFloatingLabelTextField!
var titleText: String = ""
/// Date Time
@IBOutlet weak var startDate: UIButton!
@IBOutlet weak var endDate: UIButton!
@IBOutlet weak var startTime: UILabel!
@IBOutlet weak var endTime: UILabel!
var sDate: Date = Date()
var eDate: Date = Calendar.current.date(byAdding: .hour, value: 1, to: Date())!
var isAllDay: Bool = false
@IBOutlet weak var buttonAllDay: UISwitch!
/// Notification
@IBOutlet weak var notifLabel: UILabel!
var notifText: String = "Add Notification".localiz()
var notifTop: Int = 1
var notifBot: Int? = nil
var isCustome: Bool = false
var isNotif: Bool = false
/// Member
@IBOutlet weak var tableMember: UITableView!
var memberList: [MemberList] = []
@IBOutlet weak var memberHeight: NSLayoutConstraint!
/// Repeat
@IBOutlet weak var repeatButton: UIButton!
var repeatValue: Int? = nil
var repeatText: String = "Repeat".localiz()
/// Location
@IBOutlet weak var inputLocation: SkyFloatingLabelTextField!
var locationText: String = ""
/// Description
var desc: String = ""
@IBOutlet weak var descView: UIView!
@IBOutlet weak var descViewHeight: NSLayoutConstraint!
@IBOutlet weak var descHeight: NSLayoutConstraint!
var wk: WKWebView!
let headerString: String = ""
/// Checklist
@IBOutlet weak var tableChecklist: UITableView!
var taskList: [TaskChecklist] = []
@IBOutlet weak var listHeight: NSLayoutConstraint!
/// Color
@IBOutlet weak var colorView: UIView!
var color: String = "FF944D"
/// Update
var id: Int = 0
var isUpdate: Bool = false
@IBOutlet weak var buttonSave: SSSpinnerButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "lAddTask".localiz()
self.hideKeyboardWhenTappedAround()
self.colorView.backgroundColor = UIColor.init(hexString: color)
self.buttonAllDay.isOn = self.isAllDay
self.titleTextField.text = self.titleText
self.notifLabel.text = self.notifText
self.repeatButton.setTitle(self.repeatText, for: .normal)
self.inputLocation.text = self.locationText
}
@IBAction func saveTask(_ sender: SSSpinnerButton) {
let notif = notifBot != nil ? "\(notifTop),\(notifBot ?? 1)" : "\(notifTop)"
var member: [Int] = []
for m in memberList {
member.append(m.id)
}
if self.isUpdate {
do {
let jsonData = try JSONEncoder().encode(taskList)
let update: Parameters = [
"id": id,
"title": titleTextField.text!,
"all_day": isAllDay,
"start_date": sDate.toString(dateFormat: "yyyy-MM-dd HH:mm:ss"),
"due_date": eDate.toString(dateFormat: "yyyy-MM-dd HH:mm:ss"),
"notification": notif,
"repeat": repeatValue ?? "",
"member": member,
"location": inputLocation.text ?? "",
"description": desc,
"task": jsonData,
"color": color
]
print(update)
createToDo(data: update)
}catch let error{
AlertView.instance.showAlert(title: "Error!", message: error.localizedDescription, alertType: .failure)
}
}else{
var task: [String] = []
for t in taskList {
task.append(t.task)
}
let data: [String:Any] = [
"title": titleTextField.text!,
"all_day": isAllDay,
"start_date": sDate.toString(dateFormat: "yyyy-MM-dd HH:mm:ss"),
"due_date": eDate.toString(dateFormat: "yyyy-MM-dd HH:mm:ss"),
"notification": notif,
"repeat": repeatValue ?? "",
"member": member,
"location": inputLocation.text ?? "",
"description": desc,
"task": task,
"color": color
]
createToDo(data: data)
}
}
func createToDo(data: [String:Any]) {
if !networkingClient.isConnectedToNetwork() {
return AlertView.instance.showAlert(title: "Offline", message: "NoInternet".localiz(), alertType: .failure)
}
var url = AppConstant.URL_SAVE_TODO
if self.isUpdate {
url = AppConstant.URL_UPDATE_TODO
}
guard let urlAction = URL(string: url + "?lang=" + lang) else {
return
}
let headers: HTTPHeaders = [
"Authorization": "Bearer " + (token ?? ""),
"Accept": "application/json"
]
buttonSave.startAnimate(spinnerType: .ballClipRotate, spinnercolor: .appWhite, complete: nil)
networkingClient.post(urlAction, data, headers) { (response, bad, error) in
if let error = error {
self.buttonSave.backgroundColor = UIColor.red
self.buttonSave.stopAnimationWithCompletionTypeAndBackToDefaults(completionType: .fail, backToDefaults: true){
self.buttonSave.backgroundColor = .appBNIGreen
AlertView.instance.showAlert(title: "Error!", message: error, alertType: .failure)
}
} else if let bad = bad {
self.buttonSave.backgroundColor = UIColor.red
self.buttonSave.stopAnimationWithCompletionTypeAndBackToDefaults(completionType: .fail, backToDefaults: true){
self.buttonSave.backgroundColor = .appBNIGreen
AlertView.instance.showAlert(title: "Error!", message: bad.message, alertType: .failure)
}
}else{
let jsonDecoder = JSONDecoder()
do {
let user = try jsonDecoder.decode(ApiResponse.self, from: response!)
self.buttonSave.stopAnimationWithCompletionTypeAndBackToDefaults(completionType: .success, backToDefaults: true){
AlertView.instance.showAlert(title: "Success", message: user.message, alertType: .success)
self.performSegue(withIdentifier: "closeTask", sender: self)
}
}catch let error{
self.buttonSave.backgroundColor = UIColor.red
self.buttonSave.stopAnimationWithCompletionTypeAndBackToDefaults(completionType: .fail, backToDefaults: true){
self.buttonSave.backgroundColor = .appBNIGreen
AlertView.instance.showAlert(title: "Error!", message: error.localizedDescription, alertType: .failure)
}
}
}
}
}
}
struct TaskChecklist: Codable {
let id: Int
let status: Bool
let task: String
let priority: Int
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment