我有一个detailviewcontroller,其中有一个图像视图,一个文本字段,一个文本视图和导航栏上的保存按钮。现在,当我填写详细信息并单击保存按钮时,它应该在第一个控制器(即Homeviewcontroller)中的地图上标记一个地图图钉。不知道我在哪里错了
我尝试过的一些代码。
我的HomeViewcontroller.swift文件:
import UIKit
import GoogleMaps
import CoreLocation
class HomeViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate{
var arrData = [[String:Any]]()
@IBOutlet weak var mapView: GMSMapView!
@IBOutlet weak var mapCenterPinImage: UIImageView!
@IBOutlet weak var tabBar: UITabBar!
let locationManager = CLLocationManager()
var zoom: Float = 15
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
mapView.delegate = self
mapView.settings.compassButton = true
tabBar.delegate = self
}
func pinMarker()
{
if self.arrData.count != 0
{
mapView.clear()
for item in self.arrData {
let data = item as NSDictionary
mapView.delegate = self
if let lat = data.value(forKey: "lati") as? Double, let lng = data.value(forKey: "longi") as? Double
{
let places: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat,lng)
let marker_places = GMSMarker(position: places)
marker_places.title = (data.value(forKey: "title") as! String)
marker_places.map = mapView
}
}
}
}
@IBAction func imgPickerBtn(_ sender: Any) {
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .camera
self.present(picker, animated: true, completion: nil)
}
else
{
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .photoLibrary
self.present(picker, animated: true, completion: nil)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabBar.selectedItem = self.tabBar.items?.first
let data = Defaults[.userDataResult]
self.arrData = data as! [[String:Any]]
print(self.arrData)
self.pinMarker()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImg = info[UIImagePickerControllerOriginalImage] as? UIImage {
let objDetailVC = self.storyboard?.instantiateViewController(withIdentifier: "DetailsViewController") as! DetailsViewController
self.dismiss(animated: false, completion: nil)
objDetailVC.transferedImage = pickedImg
self.navigationController?.pushViewController(objDetailVC, animated: true)
}
}
@IBAction func ZoomInBtn(_ sender: Any) {
zoom = zoom + 1
self.mapView.animate(toZoom: zoom)
}
@IBAction func zoomOutBtn(_ sender: Any) {
zoom = zoom - 1
self.mapView.animate(toZoom: zoom)
}
}
extension HomeViewController: UITabBarDelegate {
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
//This method will be called when user changes tab.
if tabBar.selectedItem?.tag == 2 {
print("tag=2")
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ListTableViewController") as! ListTableViewController
self.navigationController?.pushViewController(vc, animated: false)
}
}
}
//MARK: CLLocationManager Delegate
extension HomeViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedWhenInUse else {
return
}
locationManager.startUpdatingLocation()
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
print("Location: \(location)")
let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
zoom: zoom)
if mapView.isHidden {
mapView.isHidden = false
mapView.camera = camera
} else {
mapView.animate(to: camera)
}
}
// Handle location manager errors.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManager.stopUpdatingLocation()
print("Error: \(error)")
}
}
我的detailviewcontroller.swift文件:
import UIKit
import GoogleMaps
import CoreLocation
class DetailsViewController: UIViewController{
var picker : UIDatePicker = UIDatePicker()
@IBOutlet weak var selectedDate: UIButton!
@IBOutlet weak var detailsVCImage: UIImageView!
@IBOutlet weak var geoAddressLabel: UILabel!
@IBOutlet weak var titleTF: UITextField!
@IBOutlet weak var notesTextView: UITextView!
var imgPath = String()
var imgname = String()
let locationManager = CLLocationManager()
var currentLatitude = Double()
var currentLongitude = Double()
var mapView:GMSMapView!
var transferedImage:UIImage!
override func viewDidLoad() {
super.viewDidLoad()
notesTextView.text = "Enter Notes here...."
notesTextView.textColor = .lightGray
notesTextView.returnKeyType = .done
detailsVCImage.image = transferedImage
hideKeyboardWhenTapped()
let paddingView = UIView(frame: CGRect(x: 0,y: 0,width: 15,height: self.titleTF.frame.height))
titleTF.leftView = paddingView
titleTF.leftViewMode = .always
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
dismiss(animated: true)
}
func currentDate() -> String {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy_HH:mm:ss"
let result = formatter.string(from: date)
return result
}
func saveImg(image: UIImage) {
let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let iname = currentDate()
let fileName = "\(iname)"+".png"
let jpgData = UIImageJPEGRepresentation(detailsVCImage.image!, 1.0)
let fileurl = documentsDir.appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: fileurl.path) {
do {
try jpgData?.write(to: fileurl)
print("Image Added Successfully")
print(fileurl)
imgname = fileName
let data = Defaults[.userDataResult]
print(data)
var userFinalArray = [[String:Any]]()
var userTempArray = [[String:Any]]()
if data.count != 0 {
userTempArray = data as! [[String:Any]]
var obj = [String:Any]()
obj["title"] = self.titleTF.text
obj["notes"] = self.notesTextView.text
obj["image"] = self.imgname
obj["date"] = Date().string(format: "dd.MM.yyyy")
obj["lati"] = currentLatitude
obj["longi"] = currentLongitude
userTempArray.append(obj)
}else {
userTempArray = data as! [[String:Any]]
var obj = [String:Any]()
obj["title"] = self.titleTF.text
obj["notes"] = self.notesTextView.text
obj["image"] = self.imgname
obj["date"] = Date().string(format: "dd.MM.yyyy")
obj["lati"] = currentLatitude
obj["longi"] = currentLongitude
userTempArray.append(obj)
}
userFinalArray = userTempArray
Defaults[.userDataResult] = userFinalArray
let dataArr = Defaults[.userDataResult]
print(dataArr)
} catch {
print("error saving file", error)
}
}
}
@IBAction func datePickerTapped(_ sender: Any) {
picker.datePickerMode = UIDatePickerMode.dateAndTime
picker.addTarget(self, action: #selector(dueDateChanged(sender:)), for: UIControlEvents.valueChanged)
// self.picker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 85))
let pickerSize : CGSize = picker.sizeThatFits(CGSize.zero)
picker.frame = CGRect(x:0.0, y:442, width:pickerSize.width, height:85)
//width: 288
self.view.addSubview(picker)
}
@objc func dueDateChanged(sender:UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
selectedDate.setTitle(dateFormatter.string(from: sender.date), for: .normal)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
picker.removeFromSuperview()
}
@IBAction func saveDataTaopped(_ sender: Any) {
print("Store data in user Default")
self.navigationController?.popToRootViewController(animated: false)
saveImg(image: self.transferedImage)
}
func reverseGeocodeCoordinate(_ coordinate: CLLocationCoordinate2D) {
let geocoder = GMSGeocoder()
geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
// self.geoAddressLabel.unlock()
guard let address = response?.firstResult(), let lines = address.lines else {
return
}
self.geoAddressLabel.text = lines.joined(separator: "\n")
}
}
@IBAction func getLocationAddress(_ sender: Any) {
// reverseGeocodeCoordinate(target)
}
}
extension DetailsViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func hideKeyboardWhenTapped () {
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(DetailsViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
extension DetailsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
// reverseGeocodeCoordinate(position.target)
}
// func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
// geoAddressLabel.lock()
//
// if (gesture) {
// mapCenterPinImage.fadeIn(0.25)
// mapView.selectedMarker = nil
// }
// }
}
extension DetailsViewController: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.text == "Enter Notes here...." {
textView.text = ""
textView.textColor = .black
}
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
textView.resignFirstResponder()
}
return true
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text == "" {
textView.text = "Enter Notes here...."
textView.textColor = .lightGray
}
}
}
extension DetailsViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedWhenInUse else {
return
}
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
print("Location: \(location)")
currentLatitude = location.coordinate.latitude
currentLongitude = location.coordinate.longitude
print(currentLongitude)
print(currentLatitude)
}
// Handle location manager errors.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationManager.stopUpdatingLocation()
print("Error: \(error)")
}
}
extension Date {
func string(format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
return formatter.string(from: self)
}
}