How to pass data back with no storyboard using Swift [closed] - swift

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have 2 controllers. Let's call them A and B
Controller A is the main one and I have to check in viewWillAppear() if user exists.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let user = currentUser else {
let setupProfileViewController = SetupProfileViewController()
print("Current user empty")
let navigationController = UINavigationController(rootViewController: setupProfileViewController)
present(navigationController, animated: true, completion: nil)
return
}
}
Here user sees controller B and needs to fill data. On submit I validate all fields and create new User. Then I am dismissing B controller.
self.dismiss(animated: true) {
let matchViewController = MatchViewController()
matchViewController.currentUser = user
matchViewController.kolodaView.reloadData()
}
But what happens it A controller says there is no value in currentUser. I appreciate any advice on how to solve this.

The problem here is that
let matchViewController = MatchViewController()
matchViewController.currentUser = user
is a new instance of the class not the currently presented one , so setting user to it has no value , you have to use delegate or share your user via singleton class

Related

Is it possible to print the UI Content Presented on Screen | Swift [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Essentially I have UI View that presents on screen and takes up the entire phones screen, I would like to be able to select a button and print what is currently presented on the screen over AirPrint. Is something like this possible? Are there libraries or other ways of achieving this?
I appreciate any help.
Step 1: First for converting your UIView into image , add this extension:
extension UIView {
func toImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Step 2: Add this into your button action for print:
#IBAction func printButton(sender: AnyObject) {
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.outputType = UIPrintInfoOutputType.General
printInfo.jobName = "My UIView"
let printController = UIPrintInteractionController.sharedPrintController()
printController.printInfo = printInfo
printController.printingItem = self.view.toImage()
// If you want to specify a printer
guard let printerURL = URL(string: "Your printer URL here, e.g. ipps://HPDC4A3E0DE24A.local.:443/ipp/print") else { return }
guard let currentPrinter = UIPrinter(url: printerURL) else { return }
printController.print(to: currentPrinter, completionHandler: nil)
printController.presentFromRect(self.view.frame, inView: self.view, animated: true, completionHandler: nil)
}

Multiply methods to property in Swift [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Greeting, Everyone!
I'm wondering how implement ability to multiply methods associated to certain class
For example I've got custom class of UITextField
and I want to configurate it any way I need.
How can I handle it to get result kinda myTextField.configure().addSomeExtraFeatures().andOneMoreMethod()
like in RxSwift viewModel.fetch().rx.asObservable.bind(to: ...
Can anyone show me some direction to resolving? :) Any clue, please ๐ŸŒ
Even how properly call this process will be useful ๐Ÿ™Š๐Ÿ™‰๐Ÿ™ˆ
Return self in every function and use #discardableResult attribute so no need to care about the return.
For more about #discardableResult: https://www.avanderlee.com/swift/discardableresult/
Your UITextField custom class should be like this.
class CustomTextField: UITextField {
#discardableResult
func configure() -> Self {
// Do your code here
return self
}
#discardableResult
func addSomeExtraFeatures() -> Self {
// Do your code here
return self
}
#discardableResult
func andOneMoreMethod() -> Self {
// Do your code here
return self
}
}
Usage:
Create an instance of CustomTextField and call function.
let customTextField: CustomTextField = CustomTextField()
customTextField.configure().addSomeExtraFeatures()

How to pass value from one tabbar View item to other? [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 3 years ago.
I have a button in News Tab, And I want pass value to Competition Tab by any way.
But the problem is not passing correct value.
My code is-
//NewsViewController
#IBAction func fullStndngAction(_ sender: Any) {
//I Tried this
let prefs = UserDefaults.standard
prefs.set(true, forKey: "isFromNewsView")
//I Tried This as well
let whereFrom = storyboard?.instantiateViewController(withIdentifier: "LatestNewsDetailViewController") as? LatestNewsDetailViewController
whereFrom!.isFromNewsView = true
self.tabBarController?.selectedIndex = 1
}
But always I am getting false in competition view.
Image description-
Try one of the following solutions depending on each condition.
case 1: If your ViewController is embedded in a navigationController try this: -
if let competitionsVC = self.tabBarController.viewControllers?[1].children.first as? CompetitionViewController {
competitionVC.isFromNewsView = true
self.tabBarController?.selectedIndex = 1
}
Case 2: If your ViewController is not embedded in navigationController
if let competitionVC = self.tabBarController.viewControllers?[1] as? CompetitionViewController {
competitionVC.isFromNewsView = true
self.tabBarController?.selectedIndex = 1
}
Explanation: For case one since the VC which you are looking for is embedded in navigationController then you have cast down the way to it's child which is the VC you are looking for. For case two there is no navigationController so you cast direct to the VC you are looking for, ie.. no need to find child like on case 1.

How would I create geofences using an array of information? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to follow this tutorial on setting up geofences for locations but I want to create geofences using an array of information I have grabbed from my Firebase Database. Does anyone know how I would do that or have any tutorials they could link for me? I'm struggling to wrap my head around how I would do this as I'm pretty new to Swift. Could someone help explain what I would do or point me to someone/somewhere that could explain this?
Something like this:
func startMonitoring(_ manager:CLLocationManager, region:CLCircularRegion) {
if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
print("Cannot monitor location")
return
}
if CLLocationManager.authorizationStatus() != .authorizedAlways {
print("Please grant access")
} else {
let locationManager = CLLocationManager()
locationManager.startMonitoring(for: region)
}
}
func getRegionForLocation(_ location:CLLocation) -> CLCircularRegion {
let radiusMeters:Double = 1000
let identifier = "MyGeofence \(location)"
let region = CLCircularRegion(center: location.coordinate, radius: radiusMeters, identifier: identifier)
region.notifyOnEntry = true
region.notifyOnExit = !region.notifyOnEntry
return region
}
func getLocationsFromFireBase() -> [CLLocation] {
var locations:[CLLocation] = []
// .. populate with locations from DB
return locations
}
//where you want to enable
let locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
let locations = getLocationsFromFireBase()
for location in locations {
let region = getRegionForLocation(location)
startMonitoring(locationManager, region: region)
}
I am glossing over how to enable location access (you have to add NSLocationAlwaysUsageDescription in your info.plist for example), but the general principles of adding multiple geofences is shown. You also need to add a delegate to the CLLocationManager so you are notified when the device goes into or out of a geofence.

Swift Version 2 Bool [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm having trouble with creating an app in Swift2.
The App has an image of a wolf which changes every 0.4 seconds to reveal a running wolf.
However I have Bool errors in Swift 2 that I cannot fix.
I also have issues with declaring a void function.
Any help would be appreciated.
#IBAction func startRunnng(sender: UIButton)
{
tmrRun = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
btnGo.userInteractionEnabled = NO;
btnStop.userInteractionEnabled = YES;
sliSpeed.userInteractionEnabled = NO;
}
#IBAction func stopRunnng(sender: UIButton)
{
tmrRun invalidate()
btnGo.userInteractionEnabled = YES;
btnStop.userInteractionEnabled = NO;
sliSpeed.userInteractionEnabled = YES;
}
void takeaBound
{
String *imageName = [NSString stringWithFormat:#"wolf%d.png", pic];self.imvWolf.image = [UIImage imageNamed:imageName];
pic += 1;
if (pic == 8)
pic = 0;
}
override func viewDidLoad() {
super.viewDidLoad()
pic = 0;
// Do any additional setup after loading the view, typically from a nib.
}
Boolean values in Swift are true and false, YES and NO is used in Objective C.
So in your stopRunning method for instance, you should write:
#IBAction func stopRunnng(sender: UIButton)
{
tmrRun invalidate()
btnGo.userInteractionEnabled = true
btnStop.userInteractionEnabled = false
sliSpeed.userInteractionEnabled = true
}
(sidenote, you don't need the ; in Swift either)
About the void function. In Swift you write the return type AFTER your method declaration, starting with a ->. Like so:
func takeABound(parametersWouldGoHere) -> ()
For a void method you can write () or Void or, as you'll often do, don't write anything at all.
func takeABound(parametersWouldGoHere)
As it says in "The Swift Programming Language" in the chapter about functions
Because it does not need to return a value, the functionโ€™s definition does not include the return arrow (->) or a return type.
You can read more about functions, booleans and the like in "The Swift Programming Language", there is a nice chapter called "A Swift Tour" that will introduce you to many of the basic things.
Hope that helps