Return value from Extension Function? - ios

I have a problem in which when I select a UITextField, out pops up a view controller where the user can type into a search bar and search for particular items via the Google Places API. It looks something like this:
//When clicking on the UITextField, this function is called
#IBAction func selectLocation(){
gpaViewController.placeDelegate = self
presentViewController(gpaViewController, animated: true, completion: nil)
}
Through a the GooglePlacesAutocomplete github I found online: https://github.com/watsonbox/ios_google_places_autocomplete the below Extension was written for me so that everytime you select an entry from the UITableView from the presented gpaViewController, the place.description is printed along with its details as shown below:
extension EventFormController: GooglePlacesAutocompleteDelegate {
func placeSelected(place: Place){
var test: Place?
println(place.description)
place.getDetails { details in
println(details)
}
}
func placeViewClosed() {
dismissViewControllerAnimated(true, completion: nil)
}
}
However, upon doing so, I want it so that I can return the place.description from the placeSelected function as shown above but I am not too sure on how to do so. I tried to edit the placeSelected function inside the library but I don't think you can return anything from the didSelectRowAtIndexPath UITableView function.
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.placeSelected?(self.places[indexPath.row])
}
Any ideas on how to return the place.description and set that place.description as the text inside the UITextField after selecting an option? Any help would be appreciated!

func placeSelected(place: Place) is an protocol method, you can't change the signature by adding a return value without breaking the callback chain, i.e, if you change the signature of the protocol method, it won't be called. Instead of returing place.description from the function, you're supposed to use it for updating your UI, for example:
func placeSelected(place: Place){
var test: Place?
println(place.description)
// update UI
textField.text = place.description // assuming that your EventFormController has reference to the textField you're trying to access
place.getDetails { details in
println(details)
}
}
It would be better though if you can explain more concretely what you're trying to achieve. I still don't understand the connection between your placeSelected and the didSelectRowAtIndexPath implementations.

How about something like:
place.getDetails { details in
self.textField.text = details.name
}
I didn't read through the documentation but I believe getDetails is a function something like getDetail(completionHandler: (Details) -> Void), which completionHandler is a closure executed after details are fetched.
So I guess what you want to do after fetching the data is to let your textField in your view controller to display the information fetched.

Related

Calling viewDidLoad in another controller

I'm trying to implement a "forward message" feature in my chat app. So, when I click on the button "forward" in my chatVC the popover VC appears with the users that are on my friends list.
The question is, can I call my chatVC viewDidLoad to refresh the user information? (Otherwise, the user information would be the same as it was before clicking the "forward" button.)
Here's my code where delegate is my chatVC:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let friend = friendsList[indexPath.row]
delegate?.friendProfileImage = friend.profileImage
delegate?.friendName = friend.name
delegate?.friendId = friend.id
delegate?.friendIsOnline = friend.isOnline
delegate?.friendLastLogin = friend.lastLogin
delegate?.forwardedMessage = true
delegate?.messages = []
delegate?.collectionView.reloadData()
delegate?.loadNewMessages = false
delegate?.viewDidLoad()
dismiss(animated: true, completion: nil)
}
As a rule you should try and loosely couple independent classes as much as possible. That is one of the purposes of a delegation pattern - Class "A" can inform a delegate that something has happened and provide some data. Class A doesn't need to know (and shouldn't know) anything more about the delegate object, other than it implements the delegate method.
Your current code is tightly coupled; you are updating properties on the delegate object and reloading a collection view.
Your delegation pattern should look something like this:
protocol FriendSelectionDelegate {
func didSelectRecipient(friend: Friend)
}
Then in your pop up view controller all you need is:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let friend = friendsList[indexPath.row]
delegate?.didSelectRecipient(friend: friend)
dismiss(animated: true, completion: nil)
}
And in your ChatVC:
extension ChatVC: FriendSelectionDelegate {
func didSelectRecipient(friend: Friend) {
self.friendProfileImage = friend.profileImage
self.friendName = friend.name
self.friendId = friend.id
self.friendIsOnline = friend.isOnline
self.friendLastLogin = friend.lastLogin
self.forwardedMessage = true
self.messages = []
self.loadNewMessages = false
self.updateView()
}
}
The updateView function performs whatever operations are required to update the views. You can call that same function in your viewDidLoad to set the initial state of the views
As a further improvement, consider whether you need all of those individual properties (friendName, friendId etc). Can you just store a single property, var selectedFriend: Friend or something and access the properties from that Friend. You can then use a didSet on that selectedFriend property to call your updateView function.
You need put the code in a function that you call from viewDidLoad and your delegate

UITableViewAlertForLayoutOutsideViewHierarchy error: Warning once only (iOS 13 GM)

I am getting a strange error with iOS13 when performing a Segue and I can't figure out what it means, nor can I find any documentation for this error. The problem is that this seems to cause a lot of lag (a few seconds) until the segue is performed.
2019-09-11 22:45:38.861982+0100 Thrive[2324:414597] [TableView] Warning once only: UITableView was told to layout its visible cells
and other contents without being in the view hierarchy (the table view
or one of its superviews has not been added to a window). This may
cause bugs by forcing views inside the table view to load and perform
layout without accurate information (e.g. table view bounds, trait
collection, layout margins, safe area insets, etc), and will also
cause unnecessary performance overhead due to extra layout passes.
Make a symbolic breakpoint at
UITableViewAlertForLayoutOutsideViewHierarchy to catch this in the
debugger and see what caused this to occur, so you can avoid this
action altogether if possible, or defer it until the table view has
been added to a window. Table view: ; layer = ; contentOffset: {0, 0}; contentSize: {315, 118};
adjustedContentInset: {0, 0, 0, 0}; dataSource: >
I am using Hero but I tried disabling it and using a regular Segue and this hasn't stopped the lag.
The code to initiate the segue is didSelectRowAt
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
selectedCell = realIndexFor(activeGoalAt: indexPath)
performSegue(withIdentifier: "toGoalDetails", sender: nil)
} else if indexPath.section == 1 {
selectedCell = indexPath.row
performSegue(withIdentifier: "toIdeaDetails", sender: nil)
} else {
selectedDecision = indexPath.row
hero(destination: "DecisionDetails", type: .zoom)
}
}
And then none of the code in viewDidLoad or viewWillAppear from the destination VC affects this in any way (I tried commenting it all out with no difference.
Any idea what's causing this? I can share whatever other details are needed.
Thank you.
It happened to me because I registered the device for change orientation notification in the viewWillAppear(:) method.
I moved the registration in the viewDidAppear(:) and Xcode it's not stopping at the breakpoint anymore.
What I can say is that layout changes might be run when the view is already visible...
For people using DiffableDataSource, set animatingDifferences to false and warning will be gone.
dataSource.apply(snapshot, animatingDifferences: false)
Like #joe-h, I was getting this error and was also surprised as the unwind approach he shows is one used by lots of developers + is in some significant Apple iOS sample code.
The triggering line in my code (#joe-h, I'm guessing likely in yours, too) is a tableView.reloadRows at the selectedIndexPath (which is an unwrapped tableView.indexPathForSelectedRow):
tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
Unfortunately commenting out the row isn't an option if you are unwinding after updating the value in an existing tableView row (which is an approach in the Apple FoodTracker tutorial mentioned above, as well as one used in Apple's Everyone Can Code series). If you don't reload the row(s) then your change won't show in the tableView. After commenting out the reload in the unwind, I added a viewDidAppear with the following code and this seems to fix things:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let selectedIndexPath = tableView.indexPathForSelectedRow {
tableView.reloadRows(at: [selectedIndexPath], with: .automatic)
}
}
I'd welcome comments on whether this is a sound approach, but for now, this seems to be working.
I had the same error on my Project; A tableView with a diffable datasource. Been bugging on it for hours. Problem lies in updating the snapshot, more specifically on a background thread (default). Forcing the update of the datasource on the main thread got rid of the problem! Hope this helps someone out there!
func updateData(on annotations: [Annotation]) {
var snapshot = NSDiffableDataSourceSnapshot<AnnotationType, Annotation>()
//Append available sections
AnnotationType.allCases.forEach { snapshot.appendSections([$0]) }
//Append annotations to their corresponding sections
annotations.forEach { (annotation) in
snapshot.appendItems([annotation], toSection: annotation.type as AnnotationType)
}
//Force the update on the main thread to silence a warning about tableview not being in the hierarchy!
DispatchQueue.main.async {
self.dataSource.apply(snapshot, animatingDifferences: true)
}
}
This warning can happen du to updating table view or collection view while it is not visible, for example when it is on the parent view controller. To solve that, first, I created a property in the view controller, containing the table view to check if the view controller is visible or not, as bellow:
var isVisible: Bool = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.isVisible = true
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidAppear(animated)
self.isVisible = false
}
Then in the data source delegate, before reacting to changes, first check if the view controller is visible. If it was not, do not do any updates. For example
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
guard isVisible else { return }
tableView.beginUpdates()
}
You should check that visibility before doing any changes in the tableView. For example, in case of NSFetchedResultsController, it must be done in all delegate callbacks which we have implemented.
UPDATE
I recently found that if you update the table view with animation false, even when it is not visible, there won't be any warnings.
I'm new to Xcode/Swift so this may or may not help anyone. I started getting this error after updating to iOS 13 and Xcode 11 within the app when going back to a list from a detail view.
I found that I was doing a tableView.reloadRows and tableView.insertRows in the unwind(as suggested by Apple in one of their tutorials)
#IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? MealViewController, let meal = sourceViewController.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing meal.
meals[selectedIndexPath.row] = meal
tableView.reloadRows(at: [selectedIndexPath], with: .none)
}
else {
// Add a new meal.
let newIndexPath = IndexPath(row: meals.count, section: 0)
meals.append(meal)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
}
}
)
I commented out that section of code and it went away.
Oddly enough leaving the sort and self.tableView.reloadData() didn't give me the error.
In viewDidDisappear method I declare tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false) function. Some of you says it's not important but it affected tableView delegate methods. For example viewForHeader function is not called when I get this warning.
I found the most robust and safe way is to wait for the didMoveToWindow of the table view / collection view
as even in viewWillAppear the view may NOT be attached to a window and puting your code in viewDidAppear may cause unwanted graphical glitches
class MyTableViewOrCollectionView: UITableView {
var didMoveToWindowCallback: (()->())? = nil
override func didMoveToWindow() {
super.didMoveToWindow()
didMoveToWindowCallback?()
didMoveToWindowCallback = nil
}
}
and than you can
override func viewDidLoad() {
super.viewDidLoad()
tableView.didMoveToWindowCallback = { [weak self] in
self?.setupInitialContent()
}
}
iPadOS 13.2.3 swift 5.2 Xcode 11.2.1
Just ran into this issue only when starting the app while the device was landscape.
I was calling the detail seque in the viewDidLoad func of the master controller to make sure the detail view was setup correctly.
override func viewDidLoad() {
super.viewDidLoad()
...
self.performSegue(withIdentifier: "showDetail", sender: self)
}
When I removed the performSeque the warning not longer appeared, however,
the left bar buttons on the detail controller no longer worked properly, again only when starting the app while the device was landscape. The left most button would activate the next button to the right instead of what the first button was suppose to do.
The fix for the bar buttons was to add to the viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
...
self.splitViewController?.preferredDisplayMode = UISplitViewController.DisplayMode.allVisible
}
Then execute
override func viewWillAppear(_ animated: Bool) {
self.splitViewController?.preferredDisplayMode = UISplitViewController.DisplayMode.automatic
super.viewWillAppear(animated)
}
I have no explanation why this worked!
This app had worked flawlessly until iPados 13 was loaded.
I am getting similar breakpoint with SwiftUI, without even dealing with viewDidLoad or viewDidappear
//
// ContentView.swift
// DD
//
// Created by Roman Emperor on 3/29/20.
// Copyright © 2020 Emperors. All rights reserved.
//
import Combine
import SwiftUI
// Defining a class Booking of type Bindable Object [changed to ObservableObject]
class Booking: ObservableObject {
var didChange = PassthroughSubject<Void, Never>()
// Array of types to work with
static let types = ["Consultation", "Tooth Pain", "Cleaning", "Brases", "Dental Implant" ]
// Setting instance varibale type
var type = 0 { didSet { update() } }
func update () {
didChange.send(())
}
}
struct ContentView: View {
#ObservedObject var booking = Booking() //bindableObject in old swift version
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $booking.type, label: Text("Select a Booking Type")) {
ForEach(0 ..< Booking.types.count){
Text(Booking.types[$0]).tag($0)
}
}
}
}
.navigationBarTitle(Text("Darpan Dental Home"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The Complete output Log is here:
*> 2020-03-29 09:22:09.626082+0545 DD[1840:76404] [TableView] Warning
once only: UITableView was told to layout its visible cells and other
contents without being in the view hierarchy (the table view or one of
its superviews has not been added to a window). This may cause bugs by
forcing views inside the table view to load and perform layout without
accurate information (e.g. table view bounds, trait collection, layout
margins, safe area insets, etc), and will also cause unnecessary
performance overhead due to extra layout passes. Make a symbolic
breakpoint at UITableViewAlertForLayoutOutsideViewHierarchy to catch
this in the debugger and see what caused this to occur, so you can
avoid this action altogether if possible, or defer it until the table
view has been added to a window.*
**where is this UITableViewAlertForLayoutOutsideViewHierarchy in SwiftUI ? **
extension UIView {
func rootView() -> UIView {
var view = self
while view.superview.isNotNil {
view = view.superview!
}
return view
}
var isOnWindow: Bool {
return self.rootView() is UIWindow
}
}
then you just need to check if your tableView isOnWindow like...
if self.tableView.isOnWindow {
/// do stuff
}
Disclaimer: as the documentation explains, you may need to defer the call which means that there is no warranty your method will be called again so it's your responsibility to perform your update when isOnWindow is true.
Had the same issue, removing tableView.reloadSections fixed it. This was the line of code causing the warning:
iOS 13:
tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
in iOS 14, removing tableView.reloadSections did not fix the warning.
Or maybe your code (like mine) has nothing wrong with it and this message just randomly starts popping up. In that case, do a clean on your project, restart Xcode and watch the message magically go away!
Please check following function
override func viewWillLayoutSubviews()
For anyone that has this issue with a UISplitViewController and a UITableView inside the detail view controller, you can try subclassing and override layoutSubviews like this (From this thread):
class CustomTableView: UITableView {
override func layoutSubviews() {
if (self.window == nil) {
return
}
super.layoutSubviews()
}
}
Instead of reloading the rows inside viewDidAppear, this is what it worked for me:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.tableView.reloadRows(at: [indexPath], with: .none)
}
Also if you are using DiffableDataSource and you are selecting an indexPath manually for example, you need to do it on the completion block of the apply snapshot method:
dataSource.apply(snapshot, to: section, animatingDifferences: false, completion: {
// select the indexPath programmatically or do UITableView UI stuff here.
})
... the table view or one of its superviews has not been added to a window ...
To resolve the issue we need to check tableView.window property:
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
updateTableViewRows()
}
func dataChanged() {
updateTableViewRows()
}
func updateTableViewRows() {
if tableView.window == nil {
// TODO: just update data source
} else {
tableView.performBatchUpdates {
// TODO: update data source
// TODO: update table view cells
}
}
}
}
The idea is to not call performBatchUpdates and related functions while tableView.window is nil.

Swift / Action on UILabel Subclass, delegate method not called

I'm using ActiveLabel to handle URLs in Labels. To open a UIViewController with a WebView to display URL's Content, I want to use a delegate method.
I have tried to different ways to debug my issue.
protocol ActiveLabelURLDelegate {
func activeLabelURLDelegate(url: NSURL)
}
extension FirstVC: ActiveLabelURLDelegate {
func activeLabelURLDelegate(url: NSURL) {
print("debug activeLabelURLDelegate called") // THIS PRINT WILL NOT CALLED
let vc = stb.instantiateViewControllerWithIdentifier("SecondVC") as! SecondVC
vc.webSite = url
self.navigationController?.pushViewController(vc, animated: true)
}
}
class Cell: UITableViewCell {
#IBOutlet weak var myLabel: ActiveLabel!
var labelURLDelegate : ActiveLabelURLDelegate?
override func awakeFromNib() {
myLabel.handleURLTap { givenURL in
print("Success. You just tapped the \(givenURL) URL") // THIS PRINT IS CALLED
self.labelURLDelegate?.activeLabelURLDelegate(givenURL)
}
}
}
After this wasn't working I implemented a helping function to debug what is called.
func openURL(url: NSURL) {
print("debug openURL called") // THIS PRINT IS CALLED AS WELL
labelURLDelegate?.activeLabelURLDelegate(url)
}
Called by:
myLabel.handleURLTap { givenURL in
print("Success. You just tapped the \(givenURL) URL") // STILL CALLED
self.openURL(givenURL)
}
As you can see on the print statements, everything works till the delegate call. The delegate function activeLabelURLDelegate is not called. What am I missing? In the same Cell and same UIViewController, I'm using 4 other delegates for UIButtons and they are working perfectly.
PS: Links will be correctly displayed as Links within the UI & the correct URL is printed to the console.
It looks like you forgot to hook up the delegate. I don't see an assignment to labelURLDelegate in your cell code.

How do I display UISearchController results in a new view and not show the background of the tableView?

Quick question, I am using a UISearchController its working perfectly.
But I was wondering if it was possible to show a new view when I select the search bar?
Because when I am searching I do not want to see my tableView/background.
What you are referring to is the presentation context of the UISearchController.
Here is a link to Apple's documentation on definesPresentationContext and the relevant piece of information we care about
this property controls which existing view controller in your view
controller hierarchy is actually covered by the new content
If you are still working off this example UISearchController from before, you are already almost done and just need to look at the following line of code inside of viewDidLoad():
self.definesPresentationContext = true
The default value for this is false. Since it's set to true, we are telling the UITableViewController that it will be covered when the view controller or one of its descendants presents a view controller. In our case, we are covering the UITableViewController with the UISearchController.
To address your question, hiding the tableView/background is as simple as clearing or switching the table's data source when the search bar is active. This is handled in the following bit of code.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.userSearchController.active) {
return self.searchUsers.count
} else {
// return normal data source count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("userCell") as! UserCell
if (self.userSearchController.active && self.searchUsers.count > indexPath.row) {
// bind data to the search data source
} else {
// bind data to the normal data source
}
return cell
}
When the search bar is dismissed, we want to reload the normal data source which is done with the following:
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Clear any search criteria
searchBar.text = ""
// Force reload of table data from normal data source
}
Here's a link to a great article on UISearchControllers and also gives a brief overview of their inner workings and view hierarchy.
For future posts on SO, you should always try to include the relevant code samples so people are able to give the best feedback possible :)
EDIT
I think I misinterpreted your question a bit but the above is still relevant towards the answer. To display a special view when the search results are empty or nothing is typed in, do the following:
1) Add a new UIView as a child of the TableView of your UITableViewController in the storyboard with the desired labels/images. This will be next to any prototype cells you may have.
2) Create and wire up the outlets in your UITableViewController
#IBOutlet var emptyView: UIView!
#IBOutlet weak var emptyViewLabel: UILabel!
3) Hide the view initially in viewDidLoad()
self.emptyView?.hidden = true
4) Create a helper function to update the view
func updateEmptyView() {
if (self.userSearchController.active) {
self.emptyViewLabel.text = "Empty search data source text"
self.emptyView?.hidden = (self.searchUsers.count > 0)
} else {
// Keep the emptyView hidden or update it to use along with the normal data source
//self.emptyViewLabel.text = "Empty normal data source text"
//self.emptyView?.hidden = (self.normalDataSource.count > 0)
}
}
5) Call the updateEmptyView() after you've finished querying
func loadSearchUsers(searchString: String) {
var query = PFUser.query()
// Filter by search string
query.whereKey("username", containsString: searchString)
self.searchActive = true
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if (error == nil) {
self.searchUsers.removeAll(keepCapacity: false)
self.searchUsers += objects as! [PFUser]
self.tableView.reloadData()
self.updateEmptyView()
} else {
// Log details of the failure
println("search query error: \(error) \(error!.userInfo!)")
}
self.searchActive = false
}
}
Hope that helps!

Using A Delegate to Pass a var

I have been pulling my hair out trying to get this 'Delegate' thing to work in Swift for an App I am working on.
I have two files: CreateEvent.swift and ContactSelection.swift, where the former calls the latter.
CreateEvent's contents are:
class CreateEventViewController: UIViewController, ContactSelectionDelegate {
/...
var contactSelection: ContactSelectionViewController = ContactSelectionViewController()
override func viewDidLoad() {
super.viewDidLoad()
/...
contactSelection.delegate = self
}
func updateInvitedUsers() {
println("this finally worked")
}
func inviteButton(sender: AnyObject){
invitedLabel.text = "Invite"
invitedLabel.hidden = false
toContactSelection()
}
/...
func toContactSelection() {
let contactSelection = self.storyboard?.instantiateViewControllerWithIdentifier("ContactSelectionViewController") as ContactSelectionViewController
contactSelection.delegate = self
self.navigationController?.pushViewController(contactSelection, animated: true)
}
ContactSelection's contents are:
protocol ContactSelectionDelegate {
func updateInvitedUsers()
}
class ContactSelectionViewController: UITableViewController {
var delegate: ContactSelectionDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.delegate?.updateInvitedUsers()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Stuff
self.delegate?.updateInvitedUsers()
}
}
What am I doing wrong? I am still new and don't fully understand this subject but after scouring the Internet I can't seem to find an answer. I use the Back button available in the Navigation Bar to return to my CreateEvent view.
var contactSelection: ContactSelectionViewController = ContactSelectionViewController()
This is instantiating a view controller directly, and the value never gets used. Since it looks like you're using storyboards, this isn't a good idea since none of the outlets will be connected and you'll get optional unwrapping crashes. You set the delegate of this view controller but that's irrelevant as it doesn't get used.
It also isn't a good idea because if you do multiple pushes you'll be reusing the same view controller and this will eventually lead to bugs as you'll have leftover state from previous uses which might give you unexpected outcomes. It's better to create a new view controller to push each time.
In your code you're making a brand new contactSelection from the storyboard and pushing it without setting the delegate.
You need to set the delegate on the instance that you're pushing onto the navigation stack.
It's also helpful to pass back a reference in the delegate method which can be used to extract values, rather than relying on a separate reference in the var like you're doing.
So, I'd do the following:
Remove the var contactSelection
Add the delegate before pushing the new contactSelection object
Change the delegate method signature to this:
protocol ContactSelectionDelegate {
func updateInvitedUsers(contactSelection:ContactSelectionViewController)
}
Change your delegate calls to this:
self.delegate?.updateInvitedUsers(self)

Resources