Swift 4 Error Running Code in Extension - ios

I'm trying to upgrade my iMessage App to Swift 4. This section of example code worked perfectly in Swift 3 but gives errors when trying to move to Swift 4. The code below is in a class where the file is part of the main app target as well as the iMessage app.
#if IN_EXTENSION
// Do nothing since it's running in iMessage Extension
print("In extension")
#else
let helper = Helper()
helper.test()
UIApplication.shared.shortcutItems = []
let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let testViewController : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "Test") as UIViewController
UIApplication.shared.keyWindow?.rootViewController = testViewController
#endif
It gives errors such as shared is unavailable. Which makes total sense since it's not available in iMessage Apps.
How this worked previously is in Other Swift Flags I added -DIN_EXTENSION to the iMessage app extension but not the main app.
There are a lot of similarities between my iMessage App and main app. So I want to keep my code clean and not repeat code. So this should be possible.
I'm not sure why after converting to Swift 4 all the sudden it's throwing errors.
Any ideas on how to fix?

For some reason after rebuilding my app just now this error went away and it gave me completely different errors. After solving those this error completely went away. Seems like a bug with Xcode or something.

Related

FirebaseUI crashes when attempting to show auth picker

I'm using Firebase and FirebaseUI in my project, and on a regular basis I'm presented with the same crash when trying to log in. The user taps the Log in button and then the authentication picker is supposed to be shown, from where the user can log in with either Facebook/Google or email/password. What happens, though, is that it crashes with no error message whatsoever except for marking the following line:
struct FIRAuthLogin {
private let authUI = FUIAuth.defaultAuthUI()
private var viewController: UIViewController!
init(delegate: FIRCustomAuthDelegate, viewController: UIViewController) {
self.viewController = viewController
authUI?.delegate = delegate
authUI?.providers = [FUIGoogleAuth(), FUIFacebookAuth()]
}
func present(completion: #escaping () -> Void) {
// Exception on the line below!
let authViewController = authUI?.authViewController()
self.viewController.present(authViewController!, animated: true, completion: completion)
}
}
Even though there is an exception in the line let authViewController = authUI?.authViewController(), authViewController is not nil.
Below is an image from the stack trace (in the issue navigator):
The problem is that I'm only overriding the FUIPasswordSignUpViewController, so I'm a bit confused.
Whenever this happens, I usually just remove CocoaPods from my project and integrates it again. Then it would work correctly, but as I've done this multiple times now, and the error persist, there must an underlying error. Unfortunately, I haven't been able to reproduce the error with the FirebaseUI GitHub code, so I'm guessing the error is on my end. That's why I'm asking here instead of in the FirebaseUI-iOS GitHub repository.
It's finally fixed. I opened an issue in the FirebaseUI iOS repository, and after sending my project to one of the Google engineers, he solved it:
Looks like you're running into CocoaPods/CocoaPods#6936. Setting the build system to use the standard (not the new build system preview), deleting DerivedData, and rebuilding fixes the issue.
For the time being you'll have to not use the new build system.

Use of unresolved identifier - app development with Swift Project 2

Sorry - I realise this is a complete beginner question, but I've googled for half a day now and still can't resolve the issue myself.
I'm using xCode 8.3 and trying to complete the apple - app development with swift course - end of unit project 2. I'm told (by the Apple book) I should be able to run the app without build failures, even if it isn't finished.
I get an unresolved identifier error when I add the following code to my ViewControler file, inside the class ViewController: UIViewController.
func updateUI() {
correctWordLabel.text = game.formattedWord
scoreLabel.text = "Wins: \(totalWins), Losses: \(totalLosses)"
treeImageView.image = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)")
}
xCode suggests I change it to Game.formattedWord, but when i do get 'Instance member 'formattedWord' cannot be used on type 'Game' ViewController.Swift'.
Could someone please help?
I've checked the sample code from Apple about 100 times and they are def saying it should be game.formattedWord in the code.
Thank you!
Try correctWordLabel.text = currentGame.formattedWord
I think it’s a typo.
Earlier in your code you create an instance of the Game struct called currentGame so you are accessing the formattedWord variable inside that instance. That’s why you couldn’t change it to Game. Game is like the blueprint of the struct. currentGame is your actual ‘thing’ Hope that makes some sense.

UnitTest in swift | IOS Storyboard | Failed to cast viewcontroller class defined in objective c

So I am trying to write down some test cases for one of my controller class,
My viewcontroller is defined in objective c.
I am writing test cases in swift.
I have included my viewcontroller class in both my main target and my test target.
I have also added the storybaord in both test and main target.
In my test I am trying to load the view controller from story board, below is the code (this code is working fine in my normal project from swift class)
let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.init(for: self.classForCoder))
let viewController:UIViewController = storyboard.instantiateViewController(withIdentifier: "loginViewController")
print(viewController.classForCoder)
print(type(of: viewController))
let _ = viewController.view
controller = viewController as! LoginViewController
print output
LoginView Controller
__ABT_LoginViewController
Last line of my code is getting failedi.e
controller = viewController as! LoginViewController
error I am getting below
Could not cast value of type '__ABT_LoginViewController' (0x600000053b30) to 'LoginViewController' (0x11e88de30).
Need your help guys
Updated
So above issue resolved after following the answer by #dashandrest, Now I am facing new issue, I have created a TestAppdelegate file for test cases, in my TestAppDelegate class I have this statement import "App-swift.h now after compiling the whole code it is giving an error inside App-swift.h file mentioning cannot import module AppName, My main target module name is AppName whereas test target module name is AppNameTest,
#import "App-swift.h"
Now I am getting compiling error inside App-swift.h file.
#if defined(__has_feature) && __has_feature(modules)
#import ObjectiveC;
#import AppName; ///this line generate compile errror, module AppName not found
#import XCTest;
#endif
Updated
So there were multiple issues in my app which I resolved, definitely #DashAndRest input help me in identifying those, below are the things I correct in order to make things work.
Remove all code files from test target except the test cases.
Make sure that I have separate Module name for my main target and test target.
Make sure that My Pods file does have installing the libraries for my test target also.
Write test cases in Swift for the safe side so that I don't need to include Appname-swift.h in test cases.
Use #testable import AppModuleName (as suggested by #DashAndRest)
This is not required:
3 I have included my viewcontroller class in both my main target and my test target.
4 I have also added the storybaord in both test and main target.
Try unchecking Test target for both view controller and storyboard.
And then in your test file just include main target as:
#testable import Your-Main-Target-Name
Update
Still App-swift.h is confusing.
But if you want to test LoginViewController, here is the solution:
Add Bridging Header to your main AppName target and import all the objective-c classes to it, like:
#ifndef AppName_Bridging_Header_h
#define AppName_Bridging_Header_h
#import "LoginViewController.h"
#endif
After this, your LoginViewController class will be available for all other swift classes to use, including test target.
Add new file like LoginVCTests.swift in test target and add following code to it-
import XCTest
#testable import AppName
class LoginVCTests: XCTestCase {
func testSomeLogic() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController:UIViewController = storyboard.instantiateViewController(withIdentifier: "loginViewController") as! LoginViewController
print(viewController.classForCoder)
print(type(of: viewController))
let _ = viewController.view
//test on viewController
}
}
Hope this will solve your problem!

Add Playground to a Storyboard project: Could not find a storyboard ... in bundle NSBundle

I have a working iOS project with Storyboards. Then I added a playground file to it with following content:
The
import UIKit
import PlaygroundSupport
import SpriteKit
var str = "Hello, playground"
let gameViewController = GameViewController.loadFromStoryboard() // <<<<- Fails
PlaygroundPage.current.liveView = gameViewController
I am getting following error at line, where I loadFromStoryboard():
NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main' in bundle NSBundle
What should I fix?
There are tonnes of questions on stackoverflow with the above title/contents however, each has a very specific scenario. I have gone through many of them over past few days and I think that my scenario is distinct due to use of Playground hence I am posting again.
If this is in an existing project, you can instantiate the storyboard by using your full bundle identifier, as demonstrated here:
let myBundle = Bundle(identifier: "com.asad.MyProgram")
let storyboard = UIStoryboard(name: "MyStoryboard", bundle: myBundle)
Please note that this does require that the playground is in the same workspace as the project with that particular bundle identifier.

Initialising swift view controller with nib name in objc class

In my app I have a view controller written in Swift. I imported it in to app delegate which is written in objective c. I try to create an object of the swift view controller like this
ListAllSongsViewController *songListVC = [[ListAllSongsViewController alloc]initWithNibName:#"ListAllSongsViewController" bundle:nil];
The ListAllSongsViewController is written in swift. The project compile without any issue but when executing the above line the app crashes & stops at init method of ListAllSongsViewController
There is nothing in the log, it just stops. Zombie & All exception break points are enabled.
P.S. It only crashes in device (iOS 7.1), but works fine in simulator
Update :
Getting the same issue even if I use the default swift initialiser
ListAllSongsViewController(nibName: "ListAllSongsViewController", bundle: nil)
Usually occurs when you passed a wrong nibName. Considering it crashes only in device, I think you've made a mistake about the case of the string ListAllSongs, because the Mac/Simulator's file system is case insensitive while the device is not.

Resources