I'm having a hard time with an image download. I'm using an image URL from Firebase to download a jpeg, and using the image in a map view callout. Currently, the callout appears at the correct size but with no image or subtitle. It works perfectly when I pass in an image asset manually. The image URL is saved perfectly to the newDog object. When I debug and inspect the image, it appears in memory but looks empty.
I think maybe this has something to do with loading the callout views before the image download has completed?
Here's my viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
self.map.mapType = .standard
self.map.showsUserLocation = true
self.map.userTrackingMode = .follow
self.map.delegate = self
self.map.mapType = .hybrid
let userDogRef = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("dogs")
userDogRef.observe(.childAdded, with: { (snapshot) in
if snapshot.value == nil {
print("no new dog found")
} else {
print("new dog found")
let snapshotValue = snapshot.value as! Dictionary<String, String>
let dogID = snapshotValue["dogID"]!
let dogRef = FIRDatabase.database().reference().child("dogs").child(dogID)
dogRef.observeSingleEvent(of: .value, with: { (snap) in
print("Found dog data!")
let value = snap.value as! Dictionary<String, String>
let name = value["name"]!
let breed = value["breed"]!
let creator = value["creator"]!
let score = Int(value["score"]!)!
let lat = Double(value["latitude"]!)!
let lon = Double(value["longitude"]!)!
let url = value["imageURL"]!
let location = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let newDog = Dog()
newDog.name = name
newDog.breed = breed
newDog.creator = creator
newDog.score = score
newDog.imageURL = url
newDog.location = location
let downloadURL = URL(string: newDog.imageURL)!
URLSession.shared.dataTask(with: downloadURL, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
newDog.picture = UIImage(data: data!)!
self.dogs.append(newDog)
let annotation = CustomAnnotation(location: newDog.location, title: newDog.name, subtitle: newDog.creator)
DispatchQueue.main.async {
self.map.addAnnotation(annotation)
}
}).resume()
})
}
})
}
Here's my mapview and annotation methods:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if(annotation is MKUserLocation){
return nil
}
let ident = "pin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: ident)
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: ident)
annotationView?.canShowCallout = true
} else {
annotationView!.annotation = annotation
}
configureDetailView(annotationView!)
return annotationView
}
func configureDetailView(_ annotationView: MKAnnotationView) {
let width = 300
let height = 300
let dogPhotoView = UIView()
let views = ["dogPhotoView": dogPhotoView]
dogPhotoView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[dogPhotoView(\(height))]", options: [], metrics: nil, views: views))
dogPhotoView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[dogPhotoView(\(width))]", options: [], metrics: nil, views: views))
for dog in self.dogs {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
imageView.image = dog.picture
}
annotationView.detailCalloutAccessoryView = dogPhotoView
}
I'm using a custom annotation class. Here's that:
class CustomAnnotation: NSObject, MKAnnotation {
var coordinate : CLLocationCoordinate2D
var title: String?
var subtitle: String?
init(location: CLLocationCoordinate2D, title: String, subtitle: String) {
self.coordinate = location
self.title = title
self.subtitle = title
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Here's a photo of my debugger:
Move self.map.addAnnotation(annotation) to URLSession.shared.dataTask completion handler. Currently picture is set to Dog object after map adds annotation. Don't forget to wrap addAnnotation(_:) call with OperationQueue.main.addOperation.
dataTask works asynchronously. You should move to code to create the annotation in the completion handler.
URLSession.shared.dataTask(with: downloadURL, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
newDog.picture = UIImage(data: data!)!
self.dogs.append(newDog)
let annotation = CustomAnnotation(location: newDog.location, title: newDog.name, subtitle: newDog.creator)
DispatchQueue.main.async {
self.map.addAnnotation(annotation)
}
}).resume()
The issue occurred when I was constructing the callout image view. I created an imageView, but I didn't ever add it as a subview of it's superview. What a silly oversight! Here's the correct code:
func configureDetailView(_ annotationView: MKAnnotationView) {
let width = 300
let height = 300
let dogPhotoView = UIView()
let views = ["dogPhotoView": dogPhotoView]
dogPhotoView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[dogPhotoView(\(height))]", options: [], metrics: nil, views: views))
dogPhotoView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[dogPhotoView(\(width))]", options: [], metrics: nil, views: views))
for dog in self.dogs {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
imageView.image = dog.picture
DispatchQueue.main.async {
dogPhotoView.addSubview(imageView)
self.view.layoutIfNeeded()
}
}
annotationView.detailCalloutAccessoryView = dogPhotoView
}
Related
I want the view to be like Apple maps UI Tableview when you click on a map annotation, the UI Tableview moves up with the loaded information and it is smooth. I created a UITableView to load data from a Yelp API and Firebase database. While I do have the data loaded in the UI Tableview, there seems to be choppiness in the movement of the tableview. For example, when I first click on a map annotation, the UI Tableview will pop up, but in a random position and then after the Yelp API loads, it will move again to its default position. Another thing is that if I use a swipe gesture before the Yelp API loads, the UI Tableview will move accordingly, but then reset to its original position when the Yelp API data loads, which then I have to redo the swipe gesture.
There are many parts of this tableview, so I will provide a list of pieces of code that I use:
Note: The UI Tableview (locationInfoViews) is configured in the ViewDidLoad
Swiping up/down
func configureGestureRecognizer() {
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGesture))
swipeUp.direction = .up
addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGesture))
swipeDown.direction = .down
addGestureRecognizer(swipeDown)
}
func animateInputView(targetPosition: CGFloat, completion: #escaping(Bool) -> ()) {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {self.frame.origin.y = targetPosition}, completion: completion)
}
// MARK: - Handlers
#objc func handleSwipeGesture(sender: UISwipeGestureRecognizer) {
if sender.direction == .up {
if expansionState == .Disappeared {
animateInputView(targetPosition: self.frame.origin.y - 100) { (_) in
self.expansionState = .NotExpanded
}
}
if expansionState == .NotExpanded {
animateInputView(targetPosition: self.frame.origin.y - 200) { (_) in
self.expansionState = .PartiallyExpanded
}
}
if expansionState == .PartiallyExpanded {
animateInputView(targetPosition: self.frame.origin.y - 250) { (_) in
self.expansionState = .FullyExpanded
}
}
} else {
if expansionState == .FullyExpanded {
animateInputView(targetPosition: self.frame.origin.y + 250) { (_) in
self.expansionState = .PartiallyExpanded
}
}
if expansionState == .PartiallyExpanded {
animateInputView(targetPosition: self.frame.origin.y + 200) { (_) in
self.expansionState = .NotExpanded
}
}
if expansionState == .NotExpanded {
animateInputView(targetPosition: self.frame.origin.y + 100) { (_) in
self.expansionState = .Disappeared
}
}
}
}
When select annotation, information from Yelp and Firebase will be loaded into the location info view and the animation should move up
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
self.locationPosts.removeAll()
self.inLocationInfoMode = true
if view.annotation is MKUserLocation {
print("selected self")
} else {
self.selectedAnnotation = view.annotation as? Annotation
let coordinates = selectedAnnotation.coordinate
let coordinateRegion = MKCoordinateRegion(center: coordinates, latitudinalMeters: 1000, longitudinalMeters: 100)
mapView.setRegion(coordinateRegion, animated: true)
self.locationInfoViews.locationTitle = self.selectedAnnotation.title
// Fetch Location Post
guard let currentUid = Auth.auth().currentUser?.uid else {return}
LOCATION_REF.child(self.selectedAnnotation.title).child(currentUid).observe(.childAdded) { (snapshot) in
let postId = snapshot.key
Database.fetchLocationPost(with: postId) { (locationPost) in
self.locationPosts.append(locationPost)
self.locationPosts.sort { (post1, post2) -> Bool in
return post1.creationDate > post2.creationDate
}
self.locationInfoViews.locationResults = self.locationPosts
// self.locationInfoViews.tableView.reloadData()
// Fetch Location Information
guard let locationName = locationPost.locationName else {return}
guard let locationAddress = locationPost.address else {return}
let locationRef = COORDINATES_REF.child(locationName).child(locationAddress)
locationRef.child("mainTypeOfPlace").observe(.value) { (snapshot) in
guard let mainTypeOfPlace = snapshot.value as? String else {return}
// self.locationInfoViews.typeOfPlace = mainTypeOfPlace
locationRef.child("shortAddress").observe(.value) { (snapshot) in
guard let address1 = snapshot.value as? String else {return}
locationRef.child("city").observe(.value) { (snapshot) in
guard let city = snapshot.value as? String else {return}
locationRef.child("state").observe(.value) { (snapshot) in
guard let state = snapshot.value as? String else {return}
locationRef.child("countryCode").observe(.value) { (snapshot) in
guard let country = snapshot.value as? String else {return}
// fetch Yelp API Data
self.service.request(.match(name: locationName, address1: address1, city: city, state: state, country: country)) {
(result) in
switch result {
case .success(let response):
let businessesResponse = try? JSONDecoder().decode(BusinessesResponse.self, from: response.data)
let firstID = businessesResponse?.businesses.first?.id
self.information.request(.BusinessID(id: firstID ?? "")) {
(result) in
switch result {
case .success(let response):
if let jsonResponse = try? JSONSerialization.jsonObject(with: response.data, options: []) as? [String: Any] {
// print(jsonResponse)
if let categories = jsonResponse["categories"] as? Array<Dictionary<String, AnyObject>> {
var mainCategory = ""
for category in categories {
mainCategory = category["title"] as? String ?? ""
break
}
self.locationInfoViews.typeOfPlace = mainCategory
}
let price = jsonResponse["price"] as? String ?? ""
if let hours = jsonResponse["hours"] as? Array<Dictionary<String, AnyObject>> {
for hour in hours {
let isOpen = hour["is_open_now"] as? Int ?? 0
if isOpen == 1 {
let attributedText = NSMutableAttributedString(string: "open ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor(rgb: 0x066C19)])
attributedText.append(NSAttributedString(string: " \(price)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.black]))
self.locationInfoViews.hoursLabel.attributedText = attributedText
} else {
let attributedText = NSMutableAttributedString(string: "closed ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.red])
attributedText.append(NSAttributedString(string: " \(price)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.darkGray]))
self.locationInfoViews.hoursLabel.attributedText = attributedText
}
}
}
}
case .failure(let error):
print("Error: \(error)")
}
}
case .failure(let error):
print("Error: \(error)")
}
}
}
}
}
}
}
self.locationInfoViews.tableView.reloadData()
}
}
// enable the goButton
if inLocationInfoMode {
locationInfoViews.goButton.isEnabled = true
locationInfoViews.coordinates = selectedAnnotation.coordinate
}
// the movement of the location info view
if self.locationInfoViews.expansionState == .Disappeared {
self.locationInfoViews.animateInputView(targetPosition: self.locationInfoViews.frame.origin.y - 335) { (_) in
self.locationInfoViews.expansionState = .PartiallyExpanded
}
}
}
}
Try adding a completion block for the fetching, first extract it into a separate function. On tap on the annotation show some loading state, while you load the data. Once you receive the completion block, decide what to do depending on the result. The fetching will be done while the user sees a loading state, and no flickering will occur.
I have been trying desperately for the past few hours to make a phone call with swift when I call this function.
func callPhone(phoneNumber: String){
guard let url = URL(string:"telprompt:\(phoneNumber)") else {
print("failed to load url, phone number: \(phoneNumber)")
return
}
UIApplication.shared.open(url)
}
For some reason it doesn't work, I have researched online everywhere and still couldn't find a problem to why this wouldn't work. Some numbers would occasionally work, like if I tried "123456789" it would work. but if i try a different number it wouldn't work; The guard let statement doesn't work and the url would be empty.
Please help me. Any feedback would be very much appreciated.
Edit: So I found out when it is not working but I am not sure how to solve it. It doesn't work when I get the phone number from apple maps, but when I hard code the phone number it works.
Here is my full code:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
let regionMeters : Double = 10000
override func viewDidLoad() {
super.viewDidLoad()
map.delegate = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
map.showsUserLocation = true
if let location = locationManager.location?.coordinate {
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionMeters, longitudinalMeters: regionMeters)
map.setRegion(region, animated: true)
}
searchLocations(search: "Restaurant")
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "Place"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
let btn = UIButton(type: .contactAdd)
annotationView!.rightCalloutAccessoryView = btn
} else {
annotationView!.annotation = annotation
}
return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let subtitle = view.annotation?.subtitle as! String
let splitted = subtitle.components(separatedBy: "+")
let number = splitted.last as! String
let trimmedNumber : String = number.components(separatedBy: [" ", "-", "(", ")"]).joined()
CallOnPhone(phoneNumber: trimmedNumber)
}
func searchLocations(search : String){
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = search
searchRequest.region = map.region
let activeSearch = MKLocalSearch(request: searchRequest)
activeSearch.start { (response, err) in
if response == nil {
print("no request")
} else {
for item in (response?.mapItems)!{
let annotation = MKPointAnnotation()
annotation.title = item.name
if let phone = item.phoneNumber {
annotation.subtitle = "Phone Number: \(phone as String)"
}
annotation.coordinate = item.placemark.coordinate
self.map.addAnnotation(annotation)
}
}
}
}
#objc func CallOnPhone(phoneNumber: String){
let newStringPhone = phoneNumber.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
print(newStringPhone)
if newStringPhone != ""{
if let url = URL(string: "tel://\(newStringPhone)"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
}
Thanks,
Try trimming the phone number.
let myphone:String = phoneNumber.trimmingCharacters(in:.whitespacesAndNewlines)
Full code:
if let url = URL(string: "tel://\(myphone)"),UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler:nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
Util.shared.showToast(message: "Can't make call from this device", view: self.view)
}
Below code show calling a number on button click. Also removing space if phonenum has spaces.
var phoneNumber = "Phone Number: 1234567"
var finalNumber = ""
let number = phoneNumber.split(separator: ":")
let tempNum = "\(number.last ?? "")"
print(tempNum)
let trimmedNumber : String = tempNum.components(separatedBy: [" ", "-", "(", ")"]).joined()
print(trimmedNumber)
finalNumber = trimmedNumber
print(finalNumber)
btn_Call.addTarget(self, action: #selector(CallOnPhone), for: .touchUpInside)
#objc func CallOnPhone(sender:UIButton){
let newStringPhone = finalNumber.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
print(newStringPhone)
if newStringPhone != ""{
if let url = URL(string: "tel://\(newStringPhone)"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
I am trying to create a seat map layout functionality that takes the coordinates and create a map i want to provide the value of the sections that the map contains. I am using custom collectionViewLayout to create the cells but i am getting that error in the title .
Here is my protocol-
protocol SeatMapDelegate: class {
func getSectionCoordinates() -> [Int]
}
Definition -
func getSectionCoordinates() -> [Int] {
return sectionHeader
}
and then i am assigning the values to the array
var sectionHeader = [Int]()
sectionHeader=(delegate?.getSectionCoordinates())!
below code is my project for search and find coordinate on the map:
Maybe help you
// ViewController.swift
// MapKit Starter
//
// Created by Ehsan Amiri on 10/25/16.
// Copyright © 2016 Ehsan Amiri. All rights reserved.
//
import UIKit
import MapKit
import Foundation
class ViewController: UIViewController {
#IBOutlet var mapView: MKMapView?
#IBOutlet weak var text: UITextField!
var index = 0
var indexx = 0
let locationManager = CLLocationManager()
var picName:String?
var place :MKAnnotation?
var places = [Place]()
var place1 :MKAnnotation?
var places1 = [Place]()
override func viewDidLoad() {
super.viewDidLoad()
//downpic()
self.requestLocationAccess()
}
override func viewWillAppear(_ animated: Bool) {
let defaults = UserDefaults.standard
let age = defaults.integer(forKey: "maptype")
switch (age) {
case 0:
mapView?.mapType = .standard
case 1:
mapView?.mapType = .satellite
case 2:
mapView?.mapType = .hybrid
default:
mapView?.mapType = .standard
}
}
#IBAction func info(_ sender: Any) {
}
override var prefersStatusBarHidden: Bool {
return true
}
func requestLocationAccess() {
let status = CLLocationManager.authorizationStatus()
switch status {
case .authorizedAlways, .authorizedWhenInUse:
return
case .denied, .restricted:
print("location access denied")
default:
locationManager.requestWhenInUseAuthorization()
}
}
#IBAction func textField(_ sender: Any) {
mapView?.removeOverlays((mapView?.overlays)!)
mapView?.removeAnnotations((mapView?.annotations)!)
self.server()
_ = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.server), userInfo: nil, repeats: true)
let when = DispatchTime.now() + 1.5
DispatchQueue.main.asyncAfter(deadline: when) {
if self.indexx != 0 {
self.addAnnotations()
self.addPolyline()
}
}
}
#objc func server() {
place = nil
places = [Place]()
place1 = nil
places1 = [Place]()
indexx = 0
let id = text.text
print("id=\(id!)")
let url = URL(string: "my server")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "id=\(id!)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
let stringgg = "notFound\n\n\n\n"
if responseString == stringgg {
print(stringgg)
}else{
let json = try! JSONSerialization.jsonObject(with: data, options: [])
let betterJSON = json as! NSArray
let jsonCount = betterJSON.count
print(betterJSON)
for item in betterJSON {
self.indexx += 1
let dictionary = item as? [String : Any]
let title = dictionary?["title"] as? String
let subtitle = dictionary?["description"] as? String
let latitude = dictionary?["latitude"] as? Double ?? 0, longitude = dictionary?["longitude"] as? Double ?? 0
self.place = Place(title: title, subtitle: subtitle, coordinate: CLLocationCoordinate2DMake(latitude , longitude ))
self.places.append(self.place as! Place)
print("latttt",longitude)
if self.indexx == 1{
let shipid = UserDefaults.standard
shipid.set(title, forKey: "origin")
shipid.set(subtitle, forKey: "date")
}
if jsonCount == self.indexx{
let shipid = UserDefaults.standard
shipid.set(title, forKey: "location")
self.place1 = Place(title: title, subtitle: subtitle, coordinate: CLLocationCoordinate2DMake(latitude , longitude ))
self.places1.append(self.place1 as! Place)
}
}
}
}
task.resume()
let when = DispatchTime.now() + 1.5
DispatchQueue.main.asyncAfter(deadline: when) {
if self.indexx != 0 {
self.addAnnotations()
self.addPolyline()
}
}
}
func addAnnotations() {
print("hhhh",places)
mapView?.delegate = self
mapView?.removeAnnotations((mapView?.annotations)!)
mapView?.addAnnotations(places1)
let overlays = places1.map { MKCircle(center: $0.coordinate, radius: 100) }
mapView?.addOverlays(overlays)
}
func addPolyline() {
var locations = places.map { $0.coordinate }
let polyline = MKPolyline(coordinates: &locations, count: locations.count)
// print("Number of locations: \(locations.count)")
index = locations.capacity
mapView?.add(polyline)
}
}
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
else {
let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "annotationView") ?? MKAnnotationView()
annotationView.image = UIImage(named:"place icon")
annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
annotationView.canShowCallout = true
return annotationView
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKCircle {
let renderer = MKCircleRenderer(overlay: overlay)
renderer.fillColor = UIColor.black.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 2
return renderer
} else if overlay is MKPolyline {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.orange
renderer.lineWidth = 2
return renderer
}
return MKOverlayRenderer()
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
//guard let annotation = view.annotation as? Place, let title = annotation.title else { return }
let shipidname = text.text
let shipid = UserDefaults.standard
shipid.set(shipidname, forKey: "shipid")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "shipinfo")
self.present(secondViewController, animated: true, completion: nil)
}
}
I want show path between destination and source on google map. I am google direction api's getting route between of co-ordinates , I am getting response and set on google map but not showing on map . My code is
func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=true&mode=driving&key=AIzaSyAyU5txJ86b25-_l0DW-IldSKGGYqQJn3M")!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
DispatchQueue.main.async {
if error != nil {
print(error!.localizedDescription)
AppManager.dissmissHud()
}
else {
do {
if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
guard let routes = json["routes"] as? NSArray else {
DispatchQueue.main.async {
AppManager.dissmissHud()
}
return
}
if (routes.count > 0) {
let overview_polyline = routes[0] as? NSDictionary
let dictPolyline = overview_polyline?["overview_polyline"] as? NSDictionary
let points = dictPolyline?.object(forKey: "points") as? String
self.showPath(polyStr: points!)
DispatchQueue.main.async {
AppManager.dissmissHud()
let bounds = GMSCoordinateBounds(coordinate: source, coordinate: destination)
let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(75, 20, 20, 20))
self.vwMap!.moveCamera(update)
}
}
else {
DispatchQueue.main.async {
AppManager.dissmissHud()
}
}
}
}
catch {
print("error in JSONSerialization")
DispatchQueue.main.async {
AppManager.dissmissHud()
}
}
}
}
})
task.resume()
}
func drawPlyLineOnMap() {
let source : CLLocationCoordinate2D = CLLocationCoordinate2DMake(Double((model?.fromAddressLatitude)!), Double((model?.fromAddressLongtitude)!))
let destination : CLLocationCoordinate2D = CLLocationCoordinate2DMake(Double((model?.toAddressLatitude)!), Double((model?.toAddressLongtitude)!))
self.vwMap.clear()
//Source pin
let marker = GMSMarker()
let markerImage = UIImage(named: "from_pin")!.withRenderingMode(.alwaysOriginal)
let markerView = UIImageView(image: markerImage)
marker.position = source
marker.iconView = markerView
//marker.userData = dict
marker.map = vwMap
//Destination pin
let markerTo = GMSMarker()
let markerImageTo = UIImage(named: "to_red_pin")!.withRenderingMode(.alwaysOriginal)
let markerViewTo = UIImageView(image: markerImageTo)
markerTo.position = destination
// marker.userData = dict
markerTo.iconView = markerViewTo
markerTo.map = vwMap
var arrAdTemp:[AddressTableModel] = []
arrAdTemp.append(contentsOf: arrAddresses)
arrAdTemp.removeLast()
arrAdTemp.removeFirst()
for obj in arrAdTemp {
print(obj.strLatitude)
print(obj.strLongtitude)
let stopOver : CLLocationCoordinate2D = CLLocationCoordinate2DMake(obj.strLatitude, obj.strLongtitude)
let markerStop = GMSMarker()
let markerImageStop = UIImage(named: "to_red_pin")!.withRenderingMode(.alwaysOriginal)
let markerViewStop = UIImageView(image: markerImageStop)
markerStop.position = stopOver
//marker.userData = dict
markerStop.iconView = markerViewStop
markerStop.map = vwMap
}
self.getPolylineRoute(from: source, to: destination)
}
func showPath(polyStr :String){
let path = GMSPath(fromEncodedPath: polyStr)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.strokeColor = UIColor.black
polyline.map = vwMap // Your map view
}
I have tried lot of answer give below but not working for me. Please help me.
1st answer tried
2nd answer tried
3rd answer tried
you are setting wrong bounds so it is not showing on your map . I have tried your code it is working fine . Please change your bounds area as (0,0,0,0)
func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=true&mode=driving&key=AIzaSyAyU5txJ86b25-_l0DW-IldSKGGYqQJn3M")!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
DispatchQueue.main.async {
if error != nil {
print(error!.localizedDescription)
AppManager.dissmissHud()
}
else {
do {
if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
guard let routes = json["routes"] as? NSArray else {
DispatchQueue.main.async {
AppManager.dissmissHud()
}
return
}
if (routes.count > 0) {
let overview_polyline = routes[0] as? NSDictionary
let dictPolyline = overview_polyline?["overview_polyline"] as? NSDictionary
let points = dictPolyline?.object(forKey: "points") as? String
self.showPath(polyStr: points!)
DispatchQueue.main.async {
AppManager.dissmissHud()
let bounds = GMSCoordinateBounds(coordinate: source, coordinate: destination)
//below bounds change as 0 check it on full screen
let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(0, 0, 0, 0))
self.vwMap!.moveCamera(update)
}
}
else {
DispatchQueue.main.async {
AppManager.dissmissHud()
}
}
}
}
catch {
print("error in JSONSerialization")
DispatchQueue.main.async {
AppManager.dissmissHud()
}
}
}
}
})
task.resume()
}
I did the same using this code have a look.
{let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(self.currentLocation.coordinate.latitude),\(self.currentLocation.coordinate.longitude)&destination=\(33.6165),\(73.0962)&key=yourKey")
let request = URLRequest(url: url!)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
// notice that I can omit the types of data, response and error
do{
let json = JSON(data!)
let errornum = json["error"]
if (errornum == true){
}else{
let routes = json["routes"].array
if routes != nil && (routes?.count)! > 0{
let overViewPolyLine = routes![0]["overview_polyline"]["points"].string
let dict = routes![0].dictionaryValue
let distance = dict["legs"]?[0]["distance"]
_ = distance?["text"].stringValue
let duaration = dict["legs"]?[0]["duration"]
_ = duaration?["text"].stringValue
//dict["legs"]?["distance"]["text"].stringValue
print(overViewPolyLine!)
if overViewPolyLine != nil{
DispatchQueue.main.async() {
self.addPolyLineWithEncodedStringInMap(encodedString: overViewPolyLine!)
}
}
}
}
and then
{
func addPolyLineWithEncodedStringInMap(encodedString: String) {
let path = GMSPath(fromEncodedPath: encodedString)!
let polyLine = GMSPolyline(path: path)
polyLine.strokeWidth = 5
polyLine.strokeColor = UIColor.yellow
polyLine.map = self.googleMapsView
let center = CLLocationCoordinate2D(latitude: 33.6165, longitude: 73.0962)
let marker = GMSMarker(position: center)
marker.map = self.googleMapsView
}
func decodePolyline(encodedString: String){
let polyline = Polyline(encodedPolyline: encodedString)
let decodedCoordinates: [CLLocationCoordinate2D]? = polyline.coordinates
for coordinate in decodedCoordinates! {
let marker = GMSMarker(position: coordinate)
marker.icon = UIImage(named: "mapPin")
marker.map = self.googleMapsView
}
}
When the value of iImage is printed out it says: " size {3024, 4032} orientation 3 scale 1.000000", but then I get the error: "fatal error: unexpectedly found nil while unwrapping an Optional value" on the next line. How can the image I just got be nil?
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let iImage = info[UIImagePickerControllerOriginalImage] as! UIImage
print(iImage)
createEvent(iImage)//where it is saved to cloudkit with location and title
EventPageViewController().eventPic.image = iImage
self.dismiss(animated: true, completion: nil);
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let eventPageViewController:EventPageViewController = storyboard?.instantiateViewController(withIdentifier: "EventPage") as! EventPageViewController
self.present(eventPageViewController, animated: true, completion: nil)
}
func loadEvent(_ completion: #escaping (_ error:NSError?, _ records:[CKRecord]?) -> Void)
{
let date = NSDate(timeInterval: -60.0 * 180, since: NSDate() as Date)
let predicate = NSPredicate(format: "creationDate > %#", date)
let query = CKQuery(recordType: "Event", predicate: predicate)
CKContainer.default().publicCloudDatabase.perform(query, inZoneWith: nil){
(records, error) in
if error != nil {
print("error fetching events: \(error)")
completion(error as NSError?, nil)
} else {
print("found events")
completion(nil, records)
guard let records = records else {
return
}
for record in records
{
self.drawEvents(record["LocationF"] as! CLLocation, title1: record["StringF"] as! String)
if let asset = record["Picture"] as? CKAsset,
let data = NSData(contentsOf: asset.fileURL),
let image1 = UIImage(data: data as Data)
{
//EventPageViewController().eventPic.image = image1
}
}
}
}
}
func drawEvents(_ loc: CLLocation, title1: String)
{
mapView.delegate = self
let center = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)
let lat: CLLocationDegrees = center.latitude
let long: CLLocationDegrees = center.longitude
self.pointAnnotation1 = MKPointAnnotation()
self.pointAnnotation1.title = title1
self.pointAnnotation1.subtitle = "Event"
self.pointAnnotation1.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation1, reuseIdentifier: nil)
self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
}
This is because you are creating a new instance of your ViewController here EventPageViewController(). If this delegate method is in EventPageViewController, you can just call self.eventPic.image = iImage.
It looks like eventPic is a UIImageView as IBOutlet. So your instance of EventPageViewController hasn't finished loading its view and connecting outlets.
You should have a UIImage property in EventPageViewController.
class EventPageViewController {
var eventImage: UIImage?
#IBOutlet var eventPic:UIImageView! //you should have better name like eventImageView
func viewDidLoad() {
super.viewDidLoad()
eventPic?.image = eventImage
///rest goes here
}
}
so from you picker delegate you can access like:
let eventPageViewController = EventPageViewController()
eventPageViewController.eventImage = iImage
Hope this helps.