Commit af0eae13 by Mobile Roshka

Agreago ListaFav, Vendedor y Buscador

parent dead08ca
......@@ -16,6 +16,16 @@
BB5A72032466114400B51D4E /* APIError.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A72022466114400B51D4E /* APIError.swift */; };
BB5A72052466117C00B51D4E /* APISessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A72042466117C00B51D4E /* APISessionManager.swift */; };
BB5A7209246A1AFC00B51D4E /* FeatureCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A7208246A1AFC00B51D4E /* FeatureCollection.swift */; };
BB5A720B246CBC0600B51D4E /* CustomMarkerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A720A246CBC0600B51D4E /* CustomMarkerView.swift */; };
BB5A7238246DEFF500B51D4E /* ScreenForDetailsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A7237246DEFF400B51D4E /* ScreenForDetailsViewController.swift */; };
BB5A723A2471336A00B51D4E /* screenThreInfomationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A72392471336A00B51D4E /* screenThreInfomationViewController.swift */; };
BB5A726C2473279B00B51D4E /* ProductosPY.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = BB5A726A2473279B00B51D4E /* ProductosPY.xcdatamodeld */; };
BB5A727224732B3B00B51D4E /* Favorito.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A727124732B3B00B51D4E /* Favorito.swift */; };
BB5A727424734E7800B51D4E /* ScreenFiveFavoritesViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A727324734E7800B51D4E /* ScreenFiveFavoritesViewController.swift */; };
BB5A727624734FB600B51D4E /* FavoriteCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB5A727524734FB600B51D4E /* FavoriteCell.swift */; };
BB8DBE3824738BC6006891EF /* FavToVendorViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB8DBE3724738BC6006891EF /* FavToVendorViewController.swift */; };
BB8DBE3A2473B1E7006891EF /* DistanceVendorsCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB8DBE392473B1E7006891EF /* DistanceVendorsCell.swift */; };
BB8DBE3C2473BAFD006891EF /* FeatureWithDistance.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB8DBE3B2473BAFD006891EF /* FeatureWithDistance.swift */; };
BBDA25AB2463193100819183 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBDA25AA2463193100819183 /* AppDelegate.swift */; };
BBDA25AD2463193100819183 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBDA25AC2463193100819183 /* SceneDelegate.swift */; };
BBDA25AF2463193100819183 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBDA25AE2463193100819183 /* ViewController.swift */; };
......@@ -35,6 +45,16 @@
BB5A72022466114400B51D4E /* APIError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIError.swift; sourceTree = "<group>"; };
BB5A72042466117C00B51D4E /* APISessionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APISessionManager.swift; sourceTree = "<group>"; };
BB5A7208246A1AFC00B51D4E /* FeatureCollection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FeatureCollection.swift; sourceTree = "<group>"; };
BB5A720A246CBC0600B51D4E /* CustomMarkerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomMarkerView.swift; sourceTree = "<group>"; };
BB5A7237246DEFF400B51D4E /* ScreenForDetailsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenForDetailsViewController.swift; sourceTree = "<group>"; };
BB5A72392471336A00B51D4E /* screenThreInfomationViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = screenThreInfomationViewController.swift; sourceTree = "<group>"; };
BB5A726B2473279B00B51D4E /* ProductosPY.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = ProductosPY.xcdatamodel; sourceTree = "<group>"; };
BB5A727124732B3B00B51D4E /* Favorito.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Favorito.swift; sourceTree = "<group>"; };
BB5A727324734E7800B51D4E /* ScreenFiveFavoritesViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenFiveFavoritesViewController.swift; sourceTree = "<group>"; };
BB5A727524734FB600B51D4E /* FavoriteCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteCell.swift; sourceTree = "<group>"; };
BB8DBE3724738BC6006891EF /* FavToVendorViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavToVendorViewController.swift; sourceTree = "<group>"; };
BB8DBE392473B1E7006891EF /* DistanceVendorsCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DistanceVendorsCell.swift; sourceTree = "<group>"; };
BB8DBE3B2473BAFD006891EF /* FeatureWithDistance.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FeatureWithDistance.swift; sourceTree = "<group>"; };
BBDA25A72463193100819183 /* ProductosPY.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ProductosPY.app; sourceTree = BUILT_PRODUCTS_DIR; };
BBDA25AA2463193100819183 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
BBDA25AC2463193100819183 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
......@@ -87,6 +107,9 @@
isa = PBXGroup;
children = (
BB5A71F72465A25000B51D4E /* PageView.swift */,
BB5A720A246CBC0600B51D4E /* CustomMarkerView.swift */,
BB5A727524734FB600B51D4E /* FavoriteCell.swift */,
BB8DBE392473B1E7006891EF /* DistanceVendorsCell.swift */,
);
path = entities;
sourceTree = "<group>";
......@@ -96,6 +119,7 @@
children = (
BB5A71FA2465A5EC00B51D4E /* Constants.swift */,
BB5A7208246A1AFC00B51D4E /* FeatureCollection.swift */,
BB8DBE3B2473BAFD006891EF /* FeatureWithDistance.swift */,
);
path = structs;
sourceTree = "<group>";
......@@ -105,6 +129,10 @@
children = (
BBDA25AE2463193100819183 /* ViewController.swift */,
BB5A71FD2465C7D800B51D4E /* ScreenTwoViewController.swift */,
BB5A7237246DEFF400B51D4E /* ScreenForDetailsViewController.swift */,
BB5A72392471336A00B51D4E /* screenThreInfomationViewController.swift */,
BB5A727324734E7800B51D4E /* ScreenFiveFavoritesViewController.swift */,
BB8DBE3724738BC6006891EF /* FavToVendorViewController.swift */,
);
path = ViewControllers;
sourceTree = "<group>";
......@@ -119,6 +147,14 @@
path = utilities;
sourceTree = "<group>";
};
BB5A723E2473226900B51D4E /* entitiesCoreData */ = {
isa = PBXGroup;
children = (
BB5A727124732B3B00B51D4E /* Favorito.swift */,
);
path = entitiesCoreData;
sourceTree = "<group>";
};
BBDA259E2463193100819183 = {
isa = PBXGroup;
children = (
......@@ -140,6 +176,7 @@
BBDA25A92463193100819183 /* ProductosPY */ = {
isa = PBXGroup;
children = (
BB5A723E2473226900B51D4E /* entitiesCoreData */,
BB5A71FF24660D8600B51D4E /* utilities */,
BB5A71FC2465C7AC00B51D4E /* ViewControllers */,
BB5A71F92465A5C400B51D4E /* structs */,
......@@ -151,6 +188,7 @@
BBDA25B32463194600819183 /* Assets.xcassets */,
BBDA25B52463194600819183 /* LaunchScreen.storyboard */,
BBDA25B82463194600819183 /* Info.plist */,
BB5A726A2473279B00B51D4E /* ProductosPY.xcdatamodeld */,
);
path = ProductosPY;
sourceTree = "<group>";
......@@ -290,15 +328,25 @@
buildActionMask = 2147483647;
files = (
BB5A71FB2465A5EC00B51D4E /* Constants.swift in Sources */,
BB8DBE3824738BC6006891EF /* FavToVendorViewController.swift in Sources */,
BBDA25AF2463193100819183 /* ViewController.swift in Sources */,
BB5A72052466117C00B51D4E /* APISessionManager.swift in Sources */,
BB5A7238246DEFF500B51D4E /* ScreenForDetailsViewController.swift in Sources */,
BB5A7209246A1AFC00B51D4E /* FeatureCollection.swift in Sources */,
BB5A720B246CBC0600B51D4E /* CustomMarkerView.swift in Sources */,
BB5A726C2473279B00B51D4E /* ProductosPY.xcdatamodeld in Sources */,
BB5A71F82465A25000B51D4E /* PageView.swift in Sources */,
BB5A7201246610BE00B51D4E /* HTTPClient.swift in Sources */,
BB5A71FE2465C7D800B51D4E /* ScreenTwoViewController.swift in Sources */,
BB8DBE3C2473BAFD006891EF /* FeatureWithDistance.swift in Sources */,
BB5A72032466114400B51D4E /* APIError.swift in Sources */,
BBDA25AB2463193100819183 /* AppDelegate.swift in Sources */,
BB5A723A2471336A00B51D4E /* screenThreInfomationViewController.swift in Sources */,
BBDA25AD2463193100819183 /* SceneDelegate.swift in Sources */,
BB5A727424734E7800B51D4E /* ScreenFiveFavoritesViewController.swift in Sources */,
BB5A727224732B3B00B51D4E /* Favorito.swift in Sources */,
BB8DBE3A2473B1E7006891EF /* DistanceVendorsCell.swift in Sources */,
BB5A727624734FB600B51D4E /* FavoriteCell.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
......@@ -496,6 +544,19 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCVersionGroup section */
BB5A726A2473279B00B51D4E /* ProductosPY.xcdatamodeld */ = {
isa = XCVersionGroup;
children = (
BB5A726B2473279B00B51D4E /* ProductosPY.xcdatamodel */,
);
currentVersion = BB5A726B2473279B00B51D4E /* ProductosPY.xcdatamodel */;
path = ProductosPY.xcdatamodeld;
sourceTree = "<group>";
versionGroupType = wrapper.xcdatamodel;
};
/* End XCVersionGroup section */
};
rootObject = BBDA259F2463193100819183 /* Project object */;
}
......@@ -9,13 +9,16 @@
import UIKit
import GoogleMaps
import GooglePlaces
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if !UserDefaults.standard.bool(forKey: "Walkthrough") {
UserDefaults.standard.set(false, forKey: "Walkthrough")
}
GMSServices.provideAPIKey("AIzaSyCDCQFseYL7K7okR_YL7lmh2SCRct9YiiM")
GMSPlacesClient.provideAPIKey("AIzaSyCDCQFseYL7K7okR_YL7lmh2SCRct9YiiM")
return true
......@@ -35,6 +38,49 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ProductosPY")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="15400" systemVersion="19E287" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="FeatureData" representedClassName=".FeatureData" syncable="YES">
<attribute name="comentarios" optional="YES" attributeType="String"/>
<attribute name="contacto" optional="YES" attributeType="String"/>
<attribute name="latitude" optional="YES" attributeType="String"/>
<attribute name="longitude" optional="YES" attributeType="String"/>
<attribute name="nombre" optional="YES" attributeType="String"/>
</entity>
<elements>
<element name="FeatureData" positionX="-54" positionY="9" width="128" height="118"/>
</elements>
</model>
\ No newline at end of file
......@@ -2,6 +2,11 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlechromes</string>
<string>comgooglemaps</string>
</array>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Nos permite usar su ubicacion actual?</string>
<key>NSLocationWhenInUseUsageDescription</key>
......
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="15400" systemVersion="19E287" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="Favorito" representedClassName=".Favorito" syncable="YES">
<attribute name="comentario" attributeType="String"/>
<attribute name="contacto" attributeType="String"/>
<attribute name="latitude" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="longitude" attributeType="Double" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="nombre" attributeType="String"/>
</entity>
<elements>
<element name="Favorito" positionX="-45" positionY="0" width="128" height="118"/>
</elements>
</model>
\ No newline at end of file
//
// FavToVendorViewController.swift
// ProductosPY
//
// Created by Mobile Roshka on 5/18/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import UIKit
import CoreData
class FavToVendorViewController: UIViewController {
@IBOutlet weak var favoritoLabel: UILabel!
@IBOutlet weak var contactPhoneNumberButton: UIButton!
@IBOutlet weak var howToGetButton: UIButton!
@IBOutlet weak var addFavButton: UIButton!
@IBOutlet weak var vendorCommentaryView: UIView!
@IBOutlet weak var vendorNameLabel: UILabel!
@IBOutlet weak var vendorCommentaryLabel: UILabel!
var isData:Bool = false
var feature:Favorito? = nil
var currentCoordinates:String = ""
override func viewDidLoad() {
super.viewDidLoad()
//print("El feature es \(feature!)")
setupViews()
print("Hay dato: \(isData)")
}
func setupViews() {
vendorNameLabel.textColor = Constants.fontTitleColorVendor
vendorNameLabel.text = feature?.nombre
containCommmentary()
contactPhoneNumberButton.backgroundColor = Constants.backgroundColorButton
contactPhoneNumberButton.layer.cornerRadius = 20
contactPhoneNumberButton.setTitle("CONTACTAR", for: .normal)
//contactPhoneNumberButton.setTitleColor(UIColor.white, for: .normal)
howToGetButton.backgroundColor = Constants.backgroundColorButton
howToGetButton.layer.cornerRadius = 15
howToGetButton.setTitle("COMO LLEGAR", for: .normal)
if checkData() {
addFavButton.setImage(UIImage(named: "favSelected"), for: .normal)
favoritoLabel.text = "Quitar de favorito"
}
}
func checkData() -> Bool{
let results = fetchData()
for result in results {
if result.nombre == feature?.nombre && result.contacto == feature?.contacto {
isData = true
return true
}
}
isData = false
return false
}
func fetchData() ->[Favorito] {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Favorito>(entityName: "Favorito")
do {
let results = try context.fetch(fetchRequest)
return results
} catch {
print("No existe el dato")
}
return []
}
@IBAction func contactPhoneNumberAction(_ sender: Any) {
if let url = URL(string: "tel://\(feature?.contacto)"),UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
@IBAction func howToGetAction(_ sender: Any) {
let latDouble = feature?.latitude
let longDouble = feature?.longitude
// Primero pregunta si esta instalada la App DE GOOGLE MAPS
if let url = URL(string: "comgooglemaps://?saddr=\(currentCoordinates)&daddr=\(latDouble!),\(longDouble!)&directionsmode=driving"),UIApplication.shared.canOpenURL(url) {
print("comgoogle maps worked")
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler:nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
// Sino procede a abrir el navegador
if let url = URL(string: "https://www.google.com/maps/dir/?saddr=\(currentCoordinates)&daddr=\(latDouble!),\(longDouble!)&directionsmode=driving"),UIApplication.shared.canOpenURL(url) {
print("google com maps worked")
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler:nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
print("error hermano la cagaste")
}
}
}
@IBAction func addFavAction(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let results = fetchData()
if isData {
// Si existe el vendedor dentro del data Core se tiene que eliminar
for i in 0..<results.count {
if feature?.nombre == results[i].nombre && feature?.contacto == results[i].contacto {
context.delete(results[i])
do{
try context.save()
print("\(results[i]) borrado")
//alert(message: "Se ha quitado de favoritos", title: "Aviso")
self.performSegue(withIdentifier: "yourIdHere", sender: self)
addFavButton.setImage(UIImage(named: "favDeselected"), for: .normal)
favoritoLabel.text = "Agregar como favorito"
}catch{
print("error al borrar \(error)")
}
}
}
} else {
// Si no existe el vendedor dentro del data core Se tiene que guardar
guard let entityDescription = NSEntityDescription.entity(forEntityName: "Favorito", in: context) else { return }
let newFavorito = Favorito(entity: entityDescription, insertInto: context)
newFavorito.nombre = (feature?.nombre)!
newFavorito.comentario = (feature?.comentario)!
newFavorito.contacto = (feature?.contacto)!
newFavorito.latitude = feature!.latitude
newFavorito.longitude = feature!.longitude
do {
try context.save()
alert(message: "Se ha agregado a favoritos", title: "Aviso")
addFavButton.setImage(UIImage(named: "favSelected"), for: .normal)
favoritoLabel.text = "Quitar de favorito"
print(newFavorito)
} catch {
print("Error al guardar")
}
}
}
func containCommmentary() {
if feature?.comentario != "" {
vendorCommentaryView.isHidden = false
vendorCommentaryLabel.text = feature?.comentario
}
}
}
extension FavToVendorViewController {
func alert(message: String, title: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
//
// ScreenFiveFavoritesViewController.swift
// ProductosPY
//
// Created by Mobile Roshka on 5/18/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import UIKit
import Foundation
import CoreData
class ScreenFiveFavoritesViewController: UIViewController {
@IBOutlet weak var alertView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var favoriteTableView: UITableView!
@IBOutlet weak var mostrarMasButton: UIButton!
@IBOutlet weak var eliminarButton: UIButton!
var currentCoordinates:String = ""
var favoritos = [Favorito]()
var favSelected = Favorito()
override func viewDidLoad() {
super.viewDidLoad()
initAlertView()
initTableView()
titleLabel.textColor = Constants.fontTitleColorVendor
}
func initAlertView() {
alertView.backgroundColor = UIColor.white
alertView.layer.cornerRadius = 10
alertView.layer.shadowColor = UIColor.black.cgColor
alertView.layer.shadowOffset = .zero
alertView.layer.shadowOpacity = 0.2
alertView.layer.shadowRadius = 10.0
alertView.layer.shadowPath = UIBezierPath(rect: alertView.bounds).cgPath
alertView.layer.shouldRasterize = true
mostrarMasButton.backgroundColor = Constants.backgroundColorButton
eliminarButton.backgroundColor = UIColor(red: 0.72, green: 0.00, blue: 0.00, alpha: 1.00)
}
@IBAction func muestraVendedorAction(_ sender: Any) {
initTableView()
performSegue(withIdentifier: "favToVendorSegue", sender: favSelected)
}
@IBAction func eliminaVandedorAction(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let results = fetchData()
for i in 0..<results.count {
if favSelected.nombre == results[i].nombre && favSelected.contacto == results[i].contacto {
context.delete(results[i])
do{
try context.save()
initTableView()
}catch{
print("error al borrar \(error)")
}
}
}
}
func initTableView() {
favoritos = fetchData()
alertView.isHidden = true
favoriteTableView.isHidden = false
favoriteTableView.delegate = self
favoriteTableView.dataSource = self
favoriteTableView.reloadData()
favoriteTableView.tableFooterView = UIView(frame: .zero)
favoriteTableView.separatorColor = UIColor.clear
}
}
extension ScreenFiveFavoritesViewController: UITableViewDataSource, UITableViewDelegate {
func customCellConstuctor(cell: FavoriteCell) -> FavoriteCell {
let myCellFav = cell
myCellFav.cellView.backgroundColor = UIColor.white
myCellFav.cellView.layer.cornerRadius = 10
myCellFav.cellView.layer.shadowColor = UIColor.black.cgColor
myCellFav.cellView.layer.shadowOffset = .zero
myCellFav.cellView.layer.shadowOpacity = 0.2
myCellFav.cellView.layer.shadowRadius = 10.0
myCellFav.cellView.layer.shadowPath = UIBezierPath(rect: myCellFav.cellView.bounds).cgPath
myCellFav.cellView.layer.shouldRasterize = true
myCellFav.comentarioLabel.textColor = Constants.fontSubTextColor
myCellFav.titleLabel.textColor = Constants.fontTitleColorVendor
return myCellFav
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCellFav = tableView.dequeueReusableCell(withIdentifier: "favoritoCell", for: indexPath) as! FavoriteCell
let myCellFavCustom = customCellConstuctor(cell: myCellFav)
myCellFavCustom.titleLabel.text = favoritos[indexPath.row].nombre
myCellFavCustom.comentarioLabel.text = favoritos[indexPath.row].comentario
return myCellFav
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return favoritos.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150.0
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let id = segue.identifier
{
if id == "favToVendorSegue"
{
let feature:Favorito = sender as! Favorito
let screenFavToVendor = segue.destination as! FavToVendorViewController
screenFavToVendor.feature = feature
screenFavToVendor.currentCoordinates = currentCoordinates
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
view.bringSubviewToFront(alertView)
alertView.isHidden = false
tableView.isHidden = true
favSelected = favoritos[indexPath.row]
}
}
extension ScreenFiveFavoritesViewController {
func fetchData() ->[Favorito] {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Favorito>(entityName: "Favorito")
do {
let results = try context.fetch(fetchRequest)
return results
} catch {
print("Error al traer los datos del DataCore")
}
return []
}
@IBAction func unwindToViewControllerA(segue: UIStoryboardSegue) {
DispatchQueue.global(qos: .userInitiated).async {
DispatchQueue.main.async {
print("Entro aca")
self.initTableView()
self.alert(message: "Se ha quitado de de favoritos", title: "Aviso")
}
}
}
}
extension ScreenFiveFavoritesViewController {
func alert(message: String, title: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
//
// ScreenForDetailsViewController.swift
// ProductosPY
//
// Created by Mobile Roshka on 5/14/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import UIKit
import CoreData
class ScreenForDetailsViewController: UIViewController {
@IBOutlet weak var favoritoLabel: UILabel!
@IBOutlet weak var contactPhoneNumberButton: UIButton!
@IBOutlet weak var howToGetButton: UIButton!
@IBOutlet weak var addFavButton: UIButton!
@IBOutlet weak var vendorCommentaryView: UIView!
@IBOutlet weak var vendorNameLabel: UILabel!
@IBOutlet weak var vendorCommentaryLabel: UILabel!
var isData:Bool = false
var feature:Feature? = nil
var currentCoordinates:String = ""
override func viewDidLoad() {
super.viewDidLoad()
//print("El feature es \(feature!)")
setupViews()
print("Hay dato: \(isData)")
}
func setupViews() {
vendorNameLabel.textColor = Constants.fontTitleColorVendor
vendorNameLabel.text = feature?.properties.nombre
containCommmentary()
contactPhoneNumberButton.backgroundColor = Constants.backgroundColorButton
contactPhoneNumberButton.layer.cornerRadius = 20
contactPhoneNumberButton.setTitle("CONTACTAR", for: .normal)
//contactPhoneNumberButton.setTitleColor(UIColor.white, for: .normal)
howToGetButton.backgroundColor = Constants.backgroundColorButton
howToGetButton.layer.cornerRadius = 15
howToGetButton.setTitle("COMO LLEGAR", for: .normal)
if checkData() {
addFavButton.setImage(UIImage(named: "favSelected"), for: .normal)
favoritoLabel.text = "Quitar de favorito"
}
}
func checkData() -> Bool{
let results = fetchData()
for result in results {
if result.nombre == feature?.properties.nombre && result.contacto == feature?.properties.contacto {
isData = true
return true
}
}
isData = false
return false
}
func fetchData() ->[Favorito] {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Favorito>(entityName: "Favorito")
do {
let results = try context.fetch(fetchRequest)
return results
} catch {
print("No existe el dato")
}
return []
}
@IBAction func contactPhoneNumberAction(_ sender: Any) {
if let url = URL(string: "tel://\(feature?.properties.contacto)"),UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
@IBAction func howToGetAction(_ sender: Any) {
let latDouble = Double((feature?.geometry.coordinates[1])!)
let longDouble = Double((feature?.geometry.coordinates[0])!)
// Primero pregunta si esta instalada la App DE GOOGLE MAPS
if let url = URL(string: "comgooglemaps://?saddr=\(currentCoordinates)&daddr=\(latDouble),\(longDouble)&directionsmode=driving"),UIApplication.shared.canOpenURL(url) {
print("comgoogle maps worked")
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler:nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
// Sino procede a abrir el navegador
if let url = URL(string: "https://www.google.com/maps/dir/?saddr=\(currentCoordinates)&daddr=\(latDouble),\(longDouble)&directionsmode=driving"),UIApplication.shared.canOpenURL(url) {
print("google com maps worked")
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler:nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
print("error hermano la cagaste")
}
}
}
@IBAction func addFavAction(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let results = fetchData()
if isData {
// Si existe el vendedor dentro del data Core se tiene que eliminar
for i in 0..<results.count {
if feature?.properties.nombre == results[i].nombre && feature?.properties.contacto == results[i].contacto {
context.delete(results[i])
do{
try context.save()
print("\(results[i]) borrado")
alert(message: "Se ha quitado de favoritos", title: "Aviso")
addFavButton.setImage(UIImage(named: "favDeselected"), for: .normal)
favoritoLabel.text = "Agregar como favorito"
}catch{
print("error al borrar \(error)")
}
}
}
} else {
// Si no existe el vendedor dentro del data core Se tiene que guardar
guard let entityDescription = NSEntityDescription.entity(forEntityName: "Favorito", in: context) else { return }
let newFavorito = Favorito(entity: entityDescription, insertInto: context)
newFavorito.nombre = (feature?.properties.nombre)!
newFavorito.comentario = (feature?.properties.comentarios)!
newFavorito.contacto = (feature?.properties.contacto)!
newFavorito.latitude = (feature?.geometry.coordinates[1])!
newFavorito.longitude = (feature?.geometry.coordinates[0])!
do {
try context.save()
alert(message: "Se ha agregado a favoritos", title: "Aviso")
addFavButton.setImage(UIImage(named: "favSelected"), for: .normal)
favoritoLabel.text = "Quitar de favorito"
print(newFavorito)
} catch {
print("Error al guardar")
}
}
}
func containCommmentary() {
if feature?.properties.comentarios != "" {
vendorCommentaryView.isHidden = false
vendorCommentaryLabel.text = feature?.properties.comentarios
}
}
}
extension ScreenForDetailsViewController {
func alert(message: String, title: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
......@@ -56,15 +56,25 @@ class ViewController: UIViewController {
}
}
@IBOutlet var principalView: UIView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var pageController: UIPageControl!
@IBOutlet weak var startButton: UIButton!
let locationManager = CLLocationManager()
var locationManager: CLLocationManager!
override func viewDidAppear(_ animated: Bool) {
if UserDefaults.standard.bool(forKey: "Walkthrough") {
performSegue(withIdentifier: "screenTwoSegue", sender: nil)
} else {
principalView.isHidden = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
getCurrentLocation()
initCurrentLocation()
startButton.backgroundColor = Constants.backgroundColorButton
startButton.setTitle("Empezar", for: .normal)
startButton.setTitleColor(UIColor.white, for: .normal)
......@@ -79,23 +89,16 @@ class ViewController: UIViewController {
pageController.currentPage = 0
}
func getCurrentLocation() {
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
}
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
func initCurrentLocation() {
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
locationManager.delegate = self
}
}
// Este prosedimiento configura el scrollView segun las paginas creadas mas arriba
// Recibe como parametro una lista de paginas que luego son agregadas a lo ancho del scrollView para asi poder scrollear de forma horizontal
func configScrollView(pages: [PageView]) {
......@@ -110,6 +113,7 @@ class ViewController: UIViewController {
@IBAction func startActionButton(_ sender: Any) {
UserDefaults.standard.set(true, forKey: "Walkthrough")
performSegue(withIdentifier: "screenTwoSegue", sender: nil)
}
......@@ -127,10 +131,30 @@ extension ViewController: UIScrollViewDelegate {
}
}
// Delegates to handle events for the location manager.
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
// Handle authorization for the location manager.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted:
print("Location access was restricted.")
case .denied:
print("User denied access to location.")
case .notDetermined:
print("Location status not determined.")
case .authorizedAlways: fallthrough
case .authorizedWhenInUse:
print("Location status is OK.")
@unknown default:
fatalError()
}
}
// Handle location manager errors.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManager.stopUpdatingLocation()
print("Error: \(error)")
}
}
//
// screenThreInfomationViewController.swift
// ProductosPY
//
// Created by Mobile Roshka on 5/17/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import UIKit
class screenThreInfomationViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var terminosUsoButton: UIButton!
@IBOutlet weak var repoButton: UIButton!
@IBOutlet weak var licenciaLabel: UILabel!
@IBOutlet weak var registrarVendedorButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func terminosUsoAction(_ sender: Any) {
guard let url = URL(string: "https://productospy.org/disclaimer") else { return }
UIApplication.shared.open(url)
}
@IBAction func registrarVendedorAction(_ sender: Any) {
guard let url = URL(string: "https://productospy.org/vendor") else { return }
UIApplication.shared.open(url)
}
@IBAction func mostrarRepoAction(_ sender: Any) {
guard let url = URL(string: "https://phoebe.roshka.com/gitlab/cvargas/ProductosPY") else { return }
UIApplication.shared.open(url)
}
}
//
// CustomMarkerView.swift
// ProductosPY
// googlMapTutuorial2
//
// Created by Mobile Roshka on 5/13/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
// Created by Muskan on 12/17/17.
// Copyright © 2017 akhil. All rights reserved.
//
import Foundation
import UIKit
class CustomMarkerView: UIView {
var img: UIImage!
var borderColor: UIColor!
init(frame: CGRect, image: UIImage, borderColor: UIColor, tag: Int) {
super.init(frame: frame)
self.img=image
self.borderColor=borderColor
self.tag = tag
setupViews()
}
func setupViews() {
let imgView = UIImageView(image: img)
imgView.frame=CGRect(x: 0, y: 0, width: 50, height: 50)
imgView.layer.cornerRadius = 25
imgView.layer.borderColor=borderColor?.cgColor
imgView.layer.borderWidth=4
imgView.clipsToBounds=true
let lbl=UILabel(frame: CGRect(x: 0, y: 45, width: 50, height: 10))
lbl.text = "▾"
lbl.font=UIFont.systemFont(ofSize: 24)
lbl.textColor = borderColor
lbl.textAlignment = .center
self.addSubview(imgView)
self.addSubview(lbl)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//
// DistanceVendorsCell.swift
// ProductosPY
//
// Created by Mobile Roshka on 5/18/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import UIKit
class DistanceVendorsCell: UITableViewCell {
@IBOutlet weak var nombreLabel: UILabel!
@IBOutlet weak var comentarioLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
//
// FavoriteCell.swift
// ProductosPY
//
// Created by Mobile Roshka on 5/18/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import Foundation
import UIKit
class FavoriteCell: UITableViewCell {
@IBOutlet weak var cellView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var comentarioLabel: UILabel!
}
//
// Favorito.swift
// ProductosPY
//
// Created by Mobile Roshka on 5/18/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import UIKit
import CoreData
class Favorito: NSManagedObject {
@NSManaged var comentario:String
@NSManaged var contacto:String
@NSManaged var latitude:Double
@NSManaged var longitude:Double
@NSManaged var nombre:String
}
......@@ -14,4 +14,6 @@ struct Constants {
static let backgroundColorButton = UIColor(red: 0.08, green: 0.35, blue: 0.82, alpha: 1.00)
static let pointCurrentPageColor = UIColor(red: 0.20, green: 0.80, blue: 1.00, alpha: 1.00)
static let pointPageColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.00)
static let fontTitleColorVendor = UIColor(red: 0.00, green: 0.24, blue: 0.67, alpha: 1.00)
static let fontSubTextColor = UIColor(red: 0.71, green: 0.71, blue: 0.71, alpha: 1.00)
}
......@@ -5,28 +5,29 @@
// Created by Mobile Roshka on 5/11/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import Foundation
// MARK: - FeatureCollection
struct FeatureCollection: Codable {
let type: String?
let type: String
let features: [Feature]
}
// MARK: - Feature
struct Feature: Codable {
let type: String?
let type: FeatureType
let geometry: Geometry
let properties: Properties
}
// MARK: - Geometry
struct Geometry: Codable {
let coordinates: [Decimal]
let type: GeometryType
let coordinates: [Double?]
}
enum GeometryType: String, Codable {
case point = "Point"
}
// MARK: - Properties
......@@ -37,12 +38,57 @@ struct Properties: Codable {
// MARK: - Producto
struct Producto: Codable {
let productName, productType: String
}
let productName: ProductName
let productType: ProductType
extension Geometry {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
coordinates = [Decimal(try container.decode(Double.self, forKey: .coordinates))]
enum CodingKeys: String, CodingKey {
case productName = "product_name"
case productType = "product_type"
}
}
enum ProductName: String, Codable {
case agua = "Agua"
case alcoholEnGel = "Alcohol en gel"
case alcoholRectificado = "Alcohol rectificado"
case canastaBásica = "Canasta básica"
case cocidoQuemado = "Cocido quemado"
case comidaDulceOSalada = "Comida dulce o salada"
case costureroA = "Costurero/a"
case frutas = "Frutas"
case guantes = "Guantes"
case hipocloritoDeSodio = "Hipoclorito de sodio"
case jabónDeCoco = "Jabón de coco"
case negocioFerreteríaFarmaciaDespensaEtc = "Negocio (Ferretería, farmacia, despensa, etc)"
case papel = "Papel"
case ropaVestimenta = "Ropa, vestimenta"
case servicios = "Servicios"
case tapabocas = "Tapabocas"
case toalla = "Toalla"
case verduras = "Verduras"
}
enum ProductType: String, Codable {
case agua = "agua"
case alcoholRectificado = "alcohol_rectificado"
case canastaBasica = "canasta_basica"
case cocidoQuemado = "cocido_quemado"
case comida = "comida"
case costurera = "costurera"
case frutas = "frutas"
case gelAlcohol = "gel_alcohol"
case guantes = "guantes"
case hipocloritoSodio = "hipoclorito_sodio"
case jabonCoco = "jabon_coco"
case negocio = "negocio"
case papel = "papel"
case ropa = "ropa"
case servicios = "servicios"
case tapabocas = "tapabocas"
case toalla = "toalla"
case verduras = "verduras"
}
enum FeatureType: String, Codable {
case feature = "Feature"
}
//
// FeatureWithDistance.swift
// ProductosPY
//
// Created by Mobile Roshka on 5/18/20.
// Copyright © 2020 Mobile Roshka. All rights reserved.
//
import Foundation
struct FeatureWithDistance {
let feature:Feature
let distance:Double
let id:String
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment