I have the following code, that use goroutines and buffered channels. I want to know, if I use the channel in the right way or not.
package main
import (
"errors"
"fmt"
"math/rand"
"runtime"
"time"
)
func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}
func err1(rand int) <-chan error {
output := make(chan error, 1)
go func(n int) {
if n == 1 {
output <- errors.New("Error 1")
}
fmt.Println("Leave 1")
close(output)
}(rand)
return output
}
func err2(rand int) <-chan error {
output := make(chan error, 1)
go func(n int) {
if n == 2 {
output <- errors.New("Error 2")
}
fmt.Println("Leave 2")
close(output)
}(rand)
return output
}
func err3(rand int) <-chan error {
output := make(chan error, 1)
go func(n int) {
if n == 3 {
output <- errors.New("Error 3")
}
fmt.Println("Leave 3")
close(output)
}(rand)
return output
}
func err4(rand int) <-chan error {
output := make(chan error, 1)
go func(n int) {
if n == 3 {
output <- errors.New("Error 4")
}
fmt.Println("Leave 4")
close(output)
}(rand)
return output
}
func err5(rand int) <-chan error {
output := make(chan error, 1)
go func(n int) {
if n == 4 {
output <- errors.New("Error 5")
}
fmt.Println("Leave 5")
close(output)
}(rand)
return output
}
func process(chs ...<-chan error) error {
var err error
for _, ch := range chs {
err = <-ch
if err != nil {
//fmt.Println("Leave channel loop")
break
}
//fmt.Println("Channel loop")
}
return err
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
n := random(1, 8)
//n := 3
fmt.Println(n)
err := process(err1(n), err2(n), err3(n), err4(n), err5(n))
fmt.Println(err)
time.Sleep(time.Second * 3)
}
Related
I have a UIPickerView that I am subclassing, which works great. However, I have a method that I need to call to "reset" the UIPicker from the UIViewController in which it's being viewed. However, it never fires. How do I call func resetPicker() from another view controller?
import Foundation
import UIKit
class ScoreClockPicker: UIPickerView {
//PickerView
let timerMinutesArray = Array(00...20)
let timerSecondsArray = Array(00...59)
let periodArray = ["1st", "2nd", "3rd", "OT", "SO"]
//Picker return values
var numberOfRowsInComponentReturnValue = 0
var titleForRowReturnValue = ""
var widthForComponentReturnValue = ""
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
self.dataSource = self
}
func resetPicker() {
print("resetPicker")
self.selectRow(0, inComponent: 0, animated: true)
self.selectRow(0, inComponent: 1, animated: true)
self.selectRow(0, inComponent: 3, animated: true)
}
}
extension ScoreClockPicker: UIPickerViewDataSource {
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
numberOfRowsInComponentReturnValue = periodArray.count
} else if component == 1 {
numberOfRowsInComponentReturnValue = timerMinutesArray.count
} else if component == 2 {
numberOfRowsInComponentReturnValue = 1
} else if component == 3 {
numberOfRowsInComponentReturnValue = timerSecondsArray.count
}
return numberOfRowsInComponentReturnValue
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 4
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
var componentWidth = 0
if component == 0 {
componentWidth = 140
} else if component == 1 {
componentWidth = 40
} else if component == 2 {
componentWidth = 30
} else if component == 3 {
componentWidth = 40
}
return CGFloat(componentWidth)
}
}
extension ScoreClockPicker: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("didSelectRow")
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
titleForRowReturnValue = periodArray[row]
} else if component == 1 {
titleForRowReturnValue = String(describing: timerMinutesArray[row])
} else if component == 2 {
titleForRowReturnValue = ":"
} else if component == 3 {
titleForRowReturnValue = String(format: "%02d",timerSecondsArray[row])
}
return titleForRowReturnValue
}
}
EDIT:
The following doesn't work from the viewController calling the ScoreClockPicker:
import UIKit
class ScoreClockViewController: UIViewController {
#IBOutlet weak var resetButton: UIButton!
#IBOutlet weak var okButton: UIButton!
var picker: ScoreClockPicker?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Hide the Navigation Bar
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
//#IBOutlet
#IBAction func reset(_ sender: Any) {
print("reset")
picker?.resetPicker() //Call the ScoreClockPicker
// picker?.selectRow(0, inComponent: 0, animated: true)
// picker?.selectRow(0, inComponent: 1, animated: true)
// picker?.selectRow(0, inComponent: 3, animated: true)
}
#IBAction func ok(_ sender: Any) {
}
}
From your code you haven't initialized the picker object that you are trying to use in button action. So simply initialized the picker before using it.
If you are making outlet of ScoreClockPicker then
#IBOutlet var picker: ScoreClockPicker!
OR you can initialized picker in viewDidLoad
self.picker = ScoreClockPicker()
I have a Page Controller which the indicator Dots Disappeared! I wanted to disappear them Just In the Last Page !
I have Another Problem too
I want to move these dots +100 from bottom !
And my last question: which method can help me to write any method in any page in my page view controller ? ( I want to control all pages when the user saw that pages)
here is my code
class pageVC : UIPageViewController , UIPageViewControllerDataSource , UIPageViewControllerDelegate {
let pageVC = UIPageControl()
lazy var VCArr : [UIViewController] = {
return [self.VCInstance(name : "FirtsVC"),
self.VCInstance(name : "SecondVC"),
self.VCInstance(name :"ThirdVC"),
self.VCInstance(name :"FourthVC"),
self.VCInstance(name :"FivethVC")]
}()
private func VCInstance(name : String) -> UIViewController {
return UIStoryboard(name : "Main" , bundle : nil).instantiateViewController(withIdentifier: name)
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
if VCArr.first != nil {
print("first Page Reached!")
}
if let firstVC = VCArr.first {
setViewControllers([firstVC] , direction: .forward , animated: true, completion: nil)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let pageVC = UIPageControl()
for view in self.view.subviews {
if view is UIScrollView {
let pageControl = UIPageControl()
pageControl.pageIndicatorTintColor = UIColor.gray
pageControl.currentPageIndicatorTintColor = UIColor.white
pageControl.backgroundColor = UIColor.darkGray
pageControl.numberOfPages = VCArr.count
pageControl.center = self.view.center
self.view.addSubview(pageControl)
pageControl.layer.position.y = self.view.frame.height - 100;
}else if view is UIPageControl{
view.backgroundColor = UIColor.clear
pageVC.numberOfPages = 5
pageVC.center = self.view.center
pageVC.layer.position.y = self.view.frame.height - 180 ;
}
}
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?{
guard let viewControllerIndex = VCArr.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex-1
guard previousIndex >= 0 else {
return nil
}
guard VCArr.count > previousIndex else {
return nil
}
return VCArr[previousIndex]
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{
guard let viewControllerIndex = VCArr.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex+1
guard nextIndex < VCArr.count
else {
return nil
}
guard VCArr.count > nextIndex else {
return nil
}
if nextIndex == VCArr.count{
pageVC.isHidden = false
}
return VCArr[nextIndex]
}
public func presentationCount(for pageViewController: UIPageViewController) -> Int{
return VCArr.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int{
guard let firstViewController = viewControllers?.first , let firstViewControllerIndex = VCArr.index(of: firstViewController) else {
return 0
}
let firstIndex = firstViewControllerIndex - 1
guard firstIndex >= VCArr.count else {
return VCArr.count
}
return firstViewControllerIndex
}
public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if (VCArr.last!.isViewLoaded)
{
print("It is Done!!!")
}
}
}
here is the answer
class pageVC : UIPageViewController , UIPageViewControllerDataSource , UIPageViewControllerDelegate {
let pageVC = UIPageControl()
lazy var VCArr : [UIViewController] = {
return [self.VCInstance(name : "FirtsVC"),
self.VCInstance(name : "SecondVC"),
self.VCInstance(name :"ThirdVC"),
self.VCInstance(name :"FourthVC"),
self.VCInstance(name :"FivethVC")]
}()
private func VCInstance(name : String) -> UIViewController {
return UIStoryboard(name : "Main" , bundle : nil).instantiateViewController(withIdentifier: name)
}
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
if launchedBefore {
print("Not first launch!")
print("Should Launch MainTabBarController!")
/////Not First Time launch! reach mainTabBarController//////////
} else {
print("First launch, setting UserDefault.")
UserDefaults.standard.set(true, forKey: "launchedBefore")
}
//////Lock Rotation/////////
var shouldAutorotate: Bool {
return false
}
var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
}
func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return [UIInterfaceOrientationMask.portrait ]
}
///////Lock Roration//////
if VCArr.first != nil {
print("first Page Reached!")
}
if let firstVC = VCArr.first {
setViewControllers([firstVC] , direction: .forward , animated: true, completion: nil)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let view = self.pageVC.currentPage
for view in self.view.subviews {
if view is UIScrollView {
let pageVC = UIPageControl()
self.pageVC.pageIndicatorTintColor = UIColor.lightText
self.pageVC.currentPageIndicatorTintColor = UIColor.white
self.pageVC.backgroundColor = UIColor.white
self.pageVC.numberOfPages = VCArr.count
self.pageVC.center = self.view.center
self.view.addSubview(self.pageVC)
pageVC.layer.position.y = self.view.frame.height - 150;
}else if view is UIPageControl{
view.backgroundColor = UIColor.clear
pageVC.numberOfPages = 5
pageVC.center = self.view.center
pageVC.layer.position.y = self.view.frame.height - 100 ;
}
}
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?{
guard let viewControllerIndex = VCArr.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex-1
guard previousIndex >= 0 else {
return nil
}
guard VCArr.count > previousIndex else {
return nil
}
return VCArr[previousIndex]
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{
guard let viewControllerIndex = VCArr.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex+1
guard nextIndex < VCArr.count
else {
return nil
}
guard VCArr.count > nextIndex else {
return nil
}
return VCArr[nextIndex]
}
public func presentationCount(for pageViewController: UIPageViewController) -> Int{
return VCArr.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int{
guard let firstViewController = viewControllers?.first , let firstViewControllerIndex = VCArr.index(of: firstViewController) else {
return 0
}
let firstIndex = firstViewControllerIndex - 1
guard firstIndex >= VCArr.count else {
return VCArr.count
}
return firstViewControllerIndex
}
public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
self.pageVC.currentPage = pageViewController.viewControllers!.first!.view.tag
if(viewControllers!.first?.view.tag == 4 ) {
if (VCArr.last!.isViewLoaded)
{
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = mainStoryboard.instantiateViewController(withIdentifier: "FivethVC")
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = viewController
print("Last Page Reached!!!")
}
}
}
}
So I am new to iOS development. I am trying to make a page swipe functionality like an image carousel or like an app tutorial, and I'm Running into a Thread 1: signal SIGABRT error. in the log is states 'Can not cast value of type 'ViewController' to 'UIPageViewController'
not sure you need the entire code.
my problem line is:
self.pageViewController = self.storyboard?.instantiateViewController(withIdentifier: "contentViewController") as! UIPageViewController
help will be greatly appreciated.
class ViewController: UIViewController, UIPageViewControllerDataSource {
var pageViewController: UIPageViewController!
var pageTitles: NSArray!
var pageImages: NSArray!
override func viewDidLoad() {
self.pageTitles = NSArray(objects: " By Request","Subscription Plan","Flex Plan","Everyday Plan", "Welocme")
self.pageImages = NSArray(objects: "page1","page2","page3","page4","page5")
self.pageViewController = self.storyboard?.instantiateViewController(withIdentifier: "contentViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let startVC = self.viewControllerAtIndex(index: 0) as ContentViewController
let viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRect(x: 0, y:0, width: Int(self.view.frame.width), height: Int(self.view.frame.size.height - 60))
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMove(toParentViewController: self)
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func loginAction(_ sender: AnyObject) {
}
#IBAction func signupAction(_ sender: AnyObject) {
}
func viewControllerAtIndex(index: Int) -> ContentViewController {
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return ContentViewController()
}
var vc: ContentViewController = self.storyboard?.instantiateViewController(withIdentifier: "pageViewController") as! ContentViewController
vc.imageFile = self.pageImages[index] as! String
vc.titleText = self.pageTitles[index] as! String
vc.pageIndex = index
return vc
}
// MARK: - Page Vuew Controller Data Source
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if ((index == 0) || (index == NSNotFound)) {
return nil
}
index -= 1
return self.viewControllerAtIndex(index: index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == NSNotFound) {
return nil
}
index += 1
if (index == self.pageTitles.count) {
return nil
}
return self.viewControllerAtIndex(index: index)
}
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return self.pageTitles.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
}
I did this: "SecondViewController" is the view controller I want to go to:
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "idSegueContent" {
secondViewController = segue.destinationViewController as! SecondViewController //Error is here
}
}
public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if (error) != nil {
print(error)
}
else {
performSegue(withIdentifier: "idSegueContent", sender: self)
}
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
if let err = error {
print(error)
}
SecondViewController.dismissViewControllerAnimated(true, completion: nil)
//Error is here too
}
I am trying to login using Gmail account and show the user information in another page when the user is logged in.
You can add this code that will help you navigate to other ViewControllers:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if error != nil
{
print(error ?? "google error")
return
}
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "navigation") as! NavigationController
self.present(newViewController, animated: false, completion: nil)
// lblUserName.text = user.profile.email
}
I am having difficulties converting two sections of code from Swift 2 to Swift 3
The working Swift 2 Code Block was
func showRoute(routes: [MKRoute], time: NSTimeInterval) {
var directionsArray = [(startingAddress: String, endingAddress: String, route: MKRoute)]()
for i in 0..<routes.count {
plotPolyline(routes[i])
directionsArray += [(locationArray[i].textField.text!,
locationArray[i+1].textField.text!, routes[i])]
}
displayDirections(directionsArray)
printTimeToLabel(time)
}
Swift 3 has converted this to
func showRoute(routes: [MKRoute], time: TimeInterval) {
var directionsArray = [(startingAddress: String, endingAddress: String, route: MKRoute)]()
for i in 0..<routes.count {
plotPolyline(route: routes[i])
directionsArray += [(locationArray[i].textField?.text,
locationArray[i+1].textField?.text, routes[i])]
}
displayDirections(directionsArray: directionsArray)
printTimeToLabel(time: time)
}
This produces an error on the line
directionsArray += [(locationArray[i].textField?.text,
locationArray[i+1].textField?.text, routes[i])]
Cannot convert value of type '[(startingAddress: String, endingAddress: String, route: MKRoute)]' to expected argument type 'inout _'
If anyone can help i would really appreciate it
Just need
directionsArray += [(startingAddress : locationArray[i].textField!.text!,
endingAddress : locationArray[i+1].textField!.text!,
route : routes[i])]
I saw your question, but There are no answers. And, That is not only one problem.
Here is full body of ViewController:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController {
#IBOutlet weak var sourceField: UITextField!
#IBOutlet weak var destinationField1: UITextField!
#IBOutlet weak var destinationField2: UITextField!
#IBOutlet weak var topMarginConstraint: NSLayoutConstraint!
#IBOutlet var enterButtonArray: [UIButton]!
var originalTopMargin: CGFloat!
let locationManager = CLLocationManager()
var locationTuples: [(textField: UITextField?, mapItem: MKMapItem?)]!
var locationsArray: [(textField: UITextField?, mapItem: MKMapItem?)] {
var filtered = locationTuples.filter({ $0.mapItem != nil })
filtered += [filtered.first!]
return filtered
}
override func viewDidLoad() {
super.viewDidLoad()
originalTopMargin = topMarginConstraint.constant
locationTuples = [(sourceField, nil), (destinationField1, nil), (destinationField2, nil)]
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestLocation()
}
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.isNavigationBarHidden = true
}
#IBAction func getDirections(_ sender: AnyObject) {
view.endEditing(true)
performSegue(withIdentifier: "show_directions", sender: self)
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if locationTuples[0].mapItem == nil ||
(locationTuples[1].mapItem == nil && locationTuples[2].mapItem == nil) {
showAlert("Please enter a valid starting point and at least one destination.")
return false
} else {
return true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let directionsViewController = segue.destination as! DirectionsViewController
directionsViewController.locationArray = locationsArray
}
#IBAction func addressEntered(_ sender: UIButton) {
view.endEditing(true)
let currentTextField = locationTuples[sender.tag-1].textField
CLGeocoder().geocodeAddressString(currentTextField!.text!,
completionHandler: {(placemarks, error) -> Void in
if let placemarks = placemarks {
var addresses = [String]()
for placemark in placemarks {
addresses.append(self.formatAddressFromPlacemark(placemark))
}
self.showAddressTable(addresses, textField:currentTextField!,
placemarks:placemarks, sender:sender)
} else {
self.showAlert("Address not found.")
}
} )
}
func showAddressTable(_ addresses: [String], textField: UITextField,
placemarks: [CLPlacemark], sender: UIButton) {
let addressTableView = AddressTableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)
addressTableView.addresses = addresses
addressTableView.currentTextField = textField
addressTableView.placemarkArray = placemarks
addressTableView.mainViewController = self
addressTableView.sender = sender
addressTableView.delegate = addressTableView
addressTableView.dataSource = addressTableView
view.addSubview(addressTableView)
}
func formatAddressFromPlacemark(_ placemark: CLPlacemark) -> String {
return (placemark.addressDictionary!["FormattedAddressLines"] as! [String]).joined(separator: ", ")
}
#IBAction func swapFields(_ sender: AnyObject) {
swap(&destinationField1.text, &destinationField2.text)
swap(&locationTuples[1].mapItem, &locationTuples[2].mapItem)
swap(&self.enterButtonArray.filter{$0.tag == 2}.first!.isSelected, &self.enterButtonArray.filter{$0.tag == 3}.first!.isSelected)
}
func showAlert(_ alertString: String) {
let alert = UIAlertController(title: nil, message: alertString, preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK",
style: .cancel) { (alert) -> Void in
}
alert.addAction(okButton)
present(alert, animated: true, completion: nil)
}
// The remaining methods handle the keyboard resignation/
// move the view so that the first responders aren't hidden
func moveViewUp() {
if topMarginConstraint.constant != originalTopMargin {
return
}
topMarginConstraint.constant -= 165
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
func moveViewDown() {
if topMarginConstraint.constant == originalTopMargin {
return
}
topMarginConstraint.constant = originalTopMargin
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
})
}
}
extension ViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
enterButtonArray.filter{$0.tag == textField.tag}.first!.isSelected = false
locationTuples[textField.tag-1].mapItem = nil
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
moveViewUp()
}
func textFieldDidEndEditing(_ textField: UITextField) {
moveViewDown()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
moveViewDown()
return true
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(locations.last!,
completionHandler: {(placemarks, error) -> Void in
if let placemarks = placemarks {
let placemark = placemarks[0]
self.locationTuples[0].mapItem = MKMapItem(placemark:
MKPlacemark(coordinate: placemark.location!.coordinate,
addressDictionary: placemark.addressDictionary as! [String:AnyObject]?))
self.sourceField.text = self.formatAddressFromPlacemark(placemark)
self.enterButtonArray.filter{$0.tag == 1}.first!.isSelected = true
}
})
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}