如何在Swift 3中打开从didSelectRowAt到野生动物园的网站?

时间:2018-07-13 21:16:42

标签: ios swift

我遇到了一个问题,我实现了一种从didSelectRowAt打开URL来打开查看位置时显示的网站的方法。但是,由于某种原因,它不起作用-但我的打印语句在控制台中显示,但是没有启动它的操作。谁能检查我错过了什么。感谢您的帮助。

这是我的代码:

import UIKit
import Social
 import CoreLocation

class DetailsViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource{

  @IBOutlet weak var tableView: UITableView!

  var nearMeIndexSelected = NearMeIndexTitle()

  var place: Place!

  var coordinate :CLLocationCoordinate2D?

  var nearMeRequest : NearMeRequest!

  var locationManager = CLLocationManager()

  let infoCellId = "info-cell"
  let interactiveCellId = "interactive-cell"
  let directionsSegueId = "directions-segue"
  let gallerySegueId = "gallery-segue"
  @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
  var annotation: ARAnnotation!

  override func viewDidLoad() {
    super.viewDidLoad()

    if self.place != nil {
      self.title = place.placeName


      self.tableView.delegate = self
      self.tableView.dataSource = self
      self.loadDetailInfo()
      print("Place is not nil")
    } else {
      print("Place is nil")
    }

  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  func numberOfSections(in tableView: UITableView) -> Int {
    return 4
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
      return 4
    }
    else if section == 1 {
      return 0
    }
    else if section == 2  {
      return 1

    }
    else {
      return 1
    }

  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cellId = infoCellId
    if indexPath.section != 0 {
      cellId = interactiveCellId
    }

    let cell: UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellId)! as UITableViewCell
    var key = "Not Available"
    var value = "Not Available"

    if indexPath.section == 0  {
      if indexPath.row == 0 {
        key = "Name"
        if self.place.placeName.characters.count > 0 {
          value = self.place.placeName
        }
      } else if indexPath.row == 1 {
        key = "Address"
        if let address = self.place.address {
          if address.characters.count > 0 {
            value = address

          }
        }

      } else if indexPath.row == 2 {
        key = "Phone number"


        if let phoneNumber = self.place.phoneNumber {



          if phoneNumber.characters.count > 0 {
            value = phoneNumber



          }
        }

      } else if indexPath.row == 3 {
        key = "Website"
        if let website = self.place.website {

          if website.characters.count > 0 {
            value = website
          }
        }
      }
    }


    else if indexPath.section == 2 {
      key = "Get Directions"
    } else {
      key = "Photos of \(self.place.placeName)"
    }

    if indexPath.section == 0 {
      cell.textLabel?.text = key
      cell.detailTextLabel?.text = value
    } else {
      cell.textLabel?.text = key



    }

    return cell
  }



  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {



    // MARK: Website Opener
    if indexPath.section == 0 {

      if indexPath.row == 3 {
        print("it works")

        if let website = place.website {

        if let url = URL(string: "\(place.website)") {
          UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
      } else { return }
  }


      if indexPath.row == 1 {

        if let coordinate = place.location?.coordinate {

          if let url = URL(string:"http://maps.apple.com/maps?daddr=\(coordinate.latitude),\(coordinate.longitude)") {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
          }

        }

   }


   if indexPath.row == 2 {
        guard let phoneNumber = self.place.phoneNumber,
          phoneNumber.count > 0,

          let url = URL(string: "tel:\(phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)")

          else { return }

        if UIApplication.shared.canOpenURL(url) {
          UIApplication.shared.open(url, options: [:], completionHandler: nil)

          }

      } else { return }



}






   else if indexPath.section == 2 {
      self.performSegue(withIdentifier: directionsSegueId, sender: self)
    } else {
      if let photoReferences = self.place.photoReferences {
        if photoReferences.count != 0 {
          self.performSegue(withIdentifier: gallerySegueId, sender: self)

          return

        }
      }
      // View Photo button
      let alertController = UIAlertController(title: "No photos", message: "Sorry, but there are no photos found for this place.", preferredStyle: .alert)

      let cancelAction = UIAlertAction(title: "Ok", style: .cancel) { action in
        // ...
      }
      alertController.addAction(cancelAction)
      self.present(alertController, animated: true, completion: nil)
    }
  }

  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
      return "    Info"
    }
    else if section == 1{

      return ""
    }
    else if section == 2 {
      return "    Navigation"
    } else {
      return "    Photo"
    }
  }


  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == directionsSegueId {
      let controller = segue.destination as! DirectionsViewController
      controller.place = self.place
    } else if segue.identifier == gallerySegueId {
      let navController = segue.destination as! UINavigationController
      let galleryController = navController.viewControllers[0] as! GalleryViewController
      galleryController.place = self.place
    }
  }



  func generatePlaceUrl() -> URL {
    let placeNamePlus = self.place.placeName.replacingOccurrences(of: " ", with: "+")
    var urlString = "https://www.google.com/maps/place/" + placeNamePlus
    if let addressPlus = self.place.address?.replacingOccurrences(of: " ", with: "+") {
      urlString =  urlString + "+" + addressPlus
    }

    let url = URL.init(string: urlString)
    if let finalUrl = url {
      return finalUrl
    }

    return URL.init(string: "https://www.maps.google.com")!
  }

  func loadDetailInfo() {
    let loader = PlacesLoader()
    self.activityIndicator.startAnimating()
    self.tableView.isHidden = true
    loader.loadDetailInformation(forPlace: self.place) { (dictionary, error) in
      guard dictionary != nil else {
        DispatchQueue.main.async {
          self.activityIndicator.stopAnimating()
          self.tableView.isHidden = false
          self.tableView.reloadData()

        }

        return
      }

      if let resultDictionary = dictionary!["result"] as? NSDictionary {
        self.place.address = (resultDictionary["formatted_address"] as? String)!
        self.place.phoneNumber = resultDictionary["formatted_phone_number"] as? String
        self.place.website = resultDictionary["website"] as? String

        if let photosArr = resultDictionary["photos"] as? [NSDictionary] {
          for photoDict in photosArr {
            let photoReference = photoDict["photo_reference"] as? String
            if self.place.photoReferences == nil {
              self.place.photoReferences = [String]()
            }

            self.place.photoReferences?.append(photoReference!)
          }
        }
      }

      DispatchQueue.main.async {
        self.activityIndicator.stopAnimating()
        self.tableView.isHidden = false
        self.tableView.reloadData()

      }
    }
  }
}

1 个答案:

答案 0 :(得分:-1)

尝试此操作,因为您不强制解开place.website,所以将可选内容添加到了url中,所以它无效并且导航失败,即使if let成功[内部url检查位于UIApplication.shared.open(url内部] < / p>

if let url = URL(string:"\(place.website!)") { 
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
else {
    print("no problem")
}