Skip to content

Instantly share code, notes, and snippets.

@Banck
Created November 28, 2016 13:07
Show Gist options
  • Save Banck/44af47c90856ff1b55db4438033c31b4 to your computer and use it in GitHub Desktop.
Save Banck/44af47c90856ff1b55db4438033c31b4 to your computer and use it in GitHub Desktop.
//
// CarsSearchingViewController.swift
// finalprice
//
// Created by Сахабаев Егор on 26.11.16.
// Copyright © 2016 com.finalprice. All rights reserved.
//
import UIKit
class CarsSearchingViewController: UIViewController {
@IBOutlet var contentView : UIView!
@IBOutlet var firstSearchingLabel : UILabel!
@IBOutlet var secondSearchingLabel : UILabel!
@IBOutlet var subTitleLabel : UILabel!
@IBOutlet var titleLabel : UILabel!
@IBOutlet var mapView : MKMapView!
var jobID : String?
var jobIsComplited : Bool = false
var isFirstStart : Bool = true;
var isNotCurrentController : Bool = false
@IBOutlet var topConstaint : NSLayoutConstraint!
@IBOutlet var titleLabelWidthConstraint : NSLayoutConstraint!
@IBOutlet var subTitleBottomConstraint : NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
let latitude : Double = MainLogic.sharedInstance().userData.pickUpLocationInfo!.latitude!.toDouble()!
let longitude : Double = MainLogic.sharedInstance().userData.pickUpLocationInfo!.longitude!.toDouble()!
let centerCoord : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
self.mapView.setCenter(centerCoord, animated: false)
let annotation : MKPointAnnotation = MKPointAnnotation()
annotation.coordinate = centerCoord
isFirstStart = true
isNotCurrentController = false
let searchArray : Array<Any> = MainLogic.sharedInstance().getSearch()
if searchArray.count > 0
{
MainLogic.sharedInstance().userData.carSearch = searchArray[0] as? CarSearch
}
else
{
MainLogic.sharedInstance().userData.carSearch = MainLogic.sharedInstance().createSearch() as? CarSearch
}
let filtersDictionary : NSMutableDictionary = ["specification" : "","category" : "", "vendors" : "", "count" :""]
MainLogic.sharedInstance().userData.filtersDictionary = filtersDictionary
self.subTitleLabel.text = MainLogic.sharedInstance().userData.rentalDate
if MainLogic.sharedInstance().userData.pickUpLocationInfo?.type! == "Airport"
{
if MainLogic.sharedInstance().userData.pickUpLocationInfo == MainLogic.sharedInstance().userData.dropOffLocationInfo
{
self.titleLabel.text = "\(MainLogic.sharedInstance().userData.pickUpLocationInfo!.iata!) — \(MainLogic.sharedInstance().userData.pickUpLocationInfo!.printname!)"
}
else
{
self.titleLabel.text = "\(MainLogic.sharedInstance().userData.pickUpLocationInfo!.iata!)"
}
}
else
{
self.titleLabel.text = "\(MainLogic.sharedInstance().userData.pickUpLocationInfo!.iata!)"
}
if MainLogic.sharedInstance().userData.pickUpLocationInfo != MainLogic.sharedInstance().userData.dropOffLocationInfo
{
let dropOffLabel : UILabel = UILabel()
dropOffLabel.font = self.titleLabel.font
dropOffLabel.textColor = self.titleLabel.textColor
if MainLogic.sharedInstance().userData.dropOffLocationInfo?.type! == "Airport"
{
dropOffLabel.text = " — \(MainLogic.sharedInstance().userData.dropOffLocationInfo!.iata!)"
dropOffLabel.sizeToFit()
let pickUpLabel : UILabel = UILabel()
pickUpLabel.font = self.titleLabel.font
pickUpLabel.textColor = self.titleLabel.textColor
pickUpLabel.text = titleLabel.text
pickUpLabel.sizeToFit()
self.titleLabel.superview?.addSubview(dropOffLabel)
self.titleLabel.superview?.addSubview(pickUpLabel)
self.titleLabel.isHidden = true
pickUpLabel.sizeToFit()
if pickUpLabel.frame.size.width + dropOffLabel.frame.size.width > self.view.frame.size.width - 50*2
{
let frameX1 = (self.view.frame.size.width - 100)/2
let frameX2 = (self.view.frame.size.width - 100 - dropOffLabel.frame.size.width*2)/2
pickUpLabel.frame = CGRect(x: frameX1 - frameX2, y: pickUpLabel.frame.origin.y, w: self.view.frame.size.width - 50*2 - dropOffLabel.frame.size.width, h: pickUpLabel.frame.size.height)
}
else
{
let frameX1 = 50 + (self.view.frame.size.width - 100)/2
let frameX2 = (pickUpLabel.frame.size.width + dropOffLabel.frame.size.width)/2
pickUpLabel.frame = CGRect(x: frameX1 - frameX2, y: pickUpLabel.frame.origin.y, w: pickUpLabel.frame.size.width, h: pickUpLabel.frame.size.height)
}
pickUpLabel.textAlignment = NSTextAlignment.left
dropOffLabel.frame = CGRect(x: pickUpLabel.frame.origin.x + pickUpLabel.frame.size.width, y: pickUpLabel.frame.origin.y, w: dropOffLabel.frame.size.width, h: dropOffLabel.frame.size.height)
}
else
{
if MainLogic.sharedInstance().userData.pickUpLocationInfo?.type! == "Airport"
{
self.titleLabel.text = "\(self.titleLabel.text) — \(MainLogic.sharedInstance().userData.dropOffLocationInfo!.name!)"
}
else
{
self.titleLabel.text = MainLogic.sharedInstance().userData.pickUpLocationInfo!.name!
dropOffLabel.text = "— \(MainLogic.sharedInstance().userData.dropOffLocationInfo!.name!)"
dropOffLabel.sizeToFit()
let pickUpLabel : UILabel = UILabel(frame: self.titleLabel.frame)
pickUpLabel.font = self.titleLabel.font
pickUpLabel.textColor = self.titleLabel.textColor
pickUpLabel.font = self.titleLabel.font
pickUpLabel.text = self.titleLabel.text
self.titleLabel.superview?.addSubview(dropOffLabel)
self.titleLabel.superview?.addSubview(pickUpLabel)
self.titleLabel.isHidden = true
if pickUpLabel.frame.size.width > (self.view.frame.size.width - 50*2)/2
{
pickUpLabel.frame = CGRect(x: 50, y: pickUpLabel.frame.origin.y, w: (self.view.frame.size.width - 50*2)/2, h: pickUpLabel.frame.size.height)
}
pickUpLabel.textAlignment = NSTextAlignment.left
dropOffLabel.frame = CGRect(x: pickUpLabel.frame.origin.x + pickUpLabel.frame.size.width, y: pickUpLabel.frame.origin.y, w: self.view.frame.size.width - 50 - pickUpLabel.frame.origin.x - pickUpLabel.frame.size.width, h: dropOffLabel.frame.size.height)
dropOffLabel.sizeToFit()
if dropOffLabel.frame.size.width > (self.view.frame.size.width - 50*2)/2
{
dropOffLabel.frame = CGRect(x: dropOffLabel.frame.origin.x, y: pickUpLabel.frame.origin.y, w: self.view.frame.size.width - 50 - max(50,pickUpLabel.frame.origin.x) - pickUpLabel.frame.size.width, h: dropOffLabel.frame.size.height)
}
let frameX1 = 50 + (self.view.frame.size.width - 100)/2
let frameX2 = (dropOffLabel.frame.size.width + pickUpLabel.frame.size.width)/2
pickUpLabel.frame = CGRect(x: max(50,frameX1 - frameX2), y: pickUpLabel.frame.origin.y, w: pickUpLabel.frame.size.width, h: pickUpLabel.frame.size.height)
dropOffLabel.frame = CGRect(x: pickUpLabel.frame.origin.x + pickUpLabel.frame.size.width, y: pickUpLabel.frame.origin.y, w: dropOffLabel.frame.size.width, h: dropOffLabel.frame.size.height)
}
}
}
self.runSearch()
self.runAnimation()
}
func runAnimation()
{
if isNotCurrentController == false
{
UIView.animate(withDuration: 1.0, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
self.firstSearchingLabel.alpha = 1
self.secondSearchingLabel.alpha = 1
}, completion: { (Bool) in
UIView.animate(withDuration: 1, animations: {
self.firstSearchingLabel.alpha = 0.1
self.secondSearchingLabel.alpha = 0.1
}, completion: { (Bool) in
self.runAnimation()
})
})
}
}
/*
-(void) runAnimation
{
if (!isNotCurrentController)
[UIView animateWithDuration:1.f delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
self.firstSearchingLabel.alpha = 1.f;
self.secondSearchingLabel.alpha = 1.f;
} completion:^(BOOL finished) {
[UIView animateWithDuration:1.f animations:^{
self.firstSearchingLabel.alpha = .1f;
self.secondSearchingLabel.alpha = .1f;
} completion:^(BOOL finished) {
[self runAnimation];
}];
}];
}
*/
func runSearch()
{
let formatter : DateFormatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd"
let pickupDate : String = formatter.string(from: MainLogic.sharedInstance().userData.pickUpDate!)
let dropOffDate : String = formatter.string(from: MainLogic.sharedInstance().userData.dropOffDate!)
var pickupTime : String = (MainLogic.sharedInstance().userData.pickUpTime?.replacingOccurrences(of: ":", with: ""))!
pickupTime = pickupTime.substring(to: pickupTime.index(pickupTime.endIndex, offsetBy: -3))
var dropOffTime : String = (MainLogic.sharedInstance().userData.dropOffTime?.replacingOccurrences(of: ":", with: ""))!
dropOffTime = dropOffTime.substring(to: dropOffTime.index(dropOffTime.endIndex, offsetBy: -3))
var query : String = ""
let country : String = UserDefaults.standard.object(forKey: "country") as? String ?? (MainLogic.sharedInstance().userData.pickUpLocationInfo?.country_code)!
let currency : String = UserDefaults.standard.object(forKey: "currency") as? String ?? "USD"
let radius : Int = UserDefaults.standard.object(forKey: "radius") as? Int ?? 5
let age : Int = UserDefaults.standard.object(forKey: "age") as? Int ?? 30
let sources : String = UserDefaults.standard.object(forKey: "sources") as? String ?? ""
let test : Bool = UserDefaults.standard.bool(forKey: "test")
query = "{\"name\": \"search-car\",\"payload\": {\"test\": \(test),\"admin\": false,\"pick_up_location\": \"\(MainLogic.sharedInstance().userData.pickUpLocationInfo!.locationId!)\",\"drop_off_location\": \"\(MainLogic.sharedInstance().userData.dropOffLocationInfo!.locationId!)\",\"currency\": \"\(currency)\",\"country\": \"\(country)\",\"sources\": \"\(sources)\", \"radius\": \(radius),\"age\": \(age),\"pick_up_date\": \"\(pickupDate)\",\"pick_up_time\": \"\(pickupTime)\",\"drop_off_date\": \"\(dropOffDate)\",\"drop_off_time\": \"\(dropOffTime)\"} }"
let queryDictionary = JSONParser.parseJsonToDictionary(jsonString: query)
RequestManager.sharedInstance.showAlerts = false
RequestManager.sharedInstance.getCarOffers(params: queryDictionary as! [String : Any], url: MainLogic.getJobIdUrl(), completion: {(result : [String : Any]?, error : NSError?) in
RequestManager.sharedInstance.showAlerts = true
if error == nil
{
self.jobID = result!["job_id"] as? String
if self.jobID != nil || self.jobID != ""
{
self.perform(#selector(CarsSearchingViewController.checkJobID), with: self, afterDelay: 0.5)
}
else
{
self.alert("Oops!", message: "Something went wrong. Please, try later.", completion: {
self.backButtonWasPressed(sender: UIButton())
})
}
}
else if error!.localizedDescription.contains("offline")
{
self.alert("", message: "Please check your internet connection or try again in a few minutes", cancel: "OK", completion: {
self.backButtonWasPressed(sender: UIButton())
})
}
else
{
self.alert("Oops!", message: "Something went wrong. Please, try later", cancel: "OK", completion: {
self.backButtonWasPressed(sender: UIButton())
})
}
})
}
func checkJobID()
{
RequestManager.sharedInstance.showAlerts = false
RequestManager.sharedInstance.checkJobIdForOffers(url: "\(MainLogic.checkByJobIdUrl()!)\(jobID!)", completion: {(result : [String : Any]?, error : NSError?) in
RequestManager.sharedInstance.showAlerts = true
if error == nil || !self.isNotCurrentController
{
let jobStatus : String = result!["job_status"] as! String
if result!["result"] != nil && (result!["result"] as! [String : Any])["error"] != nil
{
DispatchQueue.main.async {
if ((result!["result"] as! [String : Any])["error"] as! String).contains("NO_OFFERS")
{
self.alert("Oops!", message: "Sorry, no offers. Please try later.", completion: {
self.backButtonWasPressed(sender: UIButton())
})
}
else
{
self.alert("Oops!", message: "Sorry, no offers. Please try later.", completion: {
self.backButtonWasPressed(sender: UIButton())
})
}
}
self.jobIsComplited = false
}
else
{
if jobStatus != "completed" && !self.isNotCurrentController
{
DispatchQueue.main.async {
self.perform(#selector(CarsSearchingViewController.checkJobID), with: self, afterDelay: 0.6)
}
}
else if jobStatus == "completed"
{
DispatchQueue.main.async {
MainLogic.sharedInstance().searchData.initWith(data: result!["result"] as! NSDictionary)
self.jobIsComplited = true
self.performSegue(withIdentifier: "toSearch", sender: self)
}
}
}
}
else if error!.localizedDescription.contains("offline")
{
DispatchQueue.main.async {
self.alert(nil, message: "Please check your internet connection or try again in a few minutes.", completion: {
self.backButtonWasPressed(sender: UIButton())
})
}
}
})
}
@IBAction func backButtonWasPressed( sender: UIButton)
{
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(CarsSearchingViewController.checkJobID), object: self)
let transition = CATransition()
transition.duration = 0.3
transition.type = kCATransitionFade
self.navigationController?.view.layer.add(transition, forKey: kCATransition)
_ = self.navigationController?.popViewController(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidDisappear(_ animated: Bool) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(CarsSearchingViewController.checkJobID), object: self)
var viewControllers = self.navigationController?.viewControllers
viewControllers?.removeObject(self)
self.navigationController?.viewControllers = viewControllers!
}
override var preferredStatusBarStyle: UIStatusBarStyle
{
return UIStatusBarStyle.lightContent
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment