Could not successfully update network info during initialization - ios

I get the above mentioned issue all the time when I first launch the app in the day.
When I first launch the app, I make server calls to get some data and then play animation video. Server calls is in a separate thread than main UI Thread.
Is it something to do with Network Reachability or the animation video ? I think the first part is the major issue but cannot recreate this all the time.
Has anyone experienced the issue ?
Below is the code when I first launch the app.
override func viewDidLoad() {
super.viewDidLoad();
self.navigationController?.navigationBarHidden = true;
self.view.backgroundColor = UIColor.whiteColor();
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
Items.setup(); //AFNetworking call
};
animationViewController.delegate = self;
animationViewController.view.autoresizesSubviews = true;
animationViewController.view.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin];
animationViewController.view.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
self.view.addSubview(animationViewController.view);
}

I have resolved this issue in Xcode 9.1 with below steps.
1.Select Simulator
2.Select Debug from top menu items.
3.Select Location from Debug menu list.
4.Select Apple location.

Check if you have an exception breakpoint to capture "All Exceptions" in breakpoint navigator. This fixed it for me.

Was experiencing this too, fixed it by giving the simulator a default location. It may be a code smell so watch how you handle the new location permissions in iOS11.

I had similar problem. Turns out in the App/Capabilities, I have Wireless Accessory Configuration with some red warnings. Click the button automatically solved the problem.
Not sure if it would work for you. I am using Xcode 8.

Issue: same with Xcode 9.0 iOS11.
Resolution: new iOS requires you to manually turn on privacy for new deployment apps. Upgrades of the app is not needed. Following these steps:
(1) iPhone "Settings" icon: click
(2) "Privacy": click
(3) "Location Services": click
(4) [Your app]: click on your app
(5) "While Using the App": click

You might have overrided loadView() without calling super method.
Change
override func loadView() {
}
To
override func loadView() {
super.loadView()
}

Related

Xcode: LaunchScreen.storyboard is not showing up

I'm trying to set up the launch screen and initial view of my app. However, I can't get either to show up.
I have this set up:
Am I missing a step? Shouldn't I be seeing a page with "blah" on it as the launch screen? Instead, when I run the simulator it's just black.
Also, I don't understand why my initial view isn't showing up either.
In my AppDelegate.swift file:
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window?.rootViewController = self.rootViewController()
return true
}
private func rootViewController() -> UIViewController {
return MapViewController.init()
}
}
And my MapViewController.swift:
import UIKit
class MapViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
label.text = "I am a test label"
self.view.addSubview(label)
NSLog("heyyyy!!") // <----------------- doesn't get printed either, so I think I'm missing something again...
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Sorry for the noob questions.
== UPDATE ==
I do get these 2 warnings when I build it:
file:///Users/emai/Documents/ios/Sherpa/SherpaNewYork/LaunchScreen.storyboard: warning: Unsupported Configuration: Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier:.
/Users/emai/Documents/ios/Sherpa/SherpaNewYork/LaunchScreen.storyboard:9: Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier:.
I also struggled with a launchscreen storyboard not showing up. I tried everything fix I could find to no avail. Then I cleared the cache on my Simulator and it worked! Turned out it was a simulator problem. I cleared the cache with this command in terminal: xcrun simctl erase all
It looks like you haven't set up your storyboards with an entry point. Set up the first scene you want to show as the Initial View Controller
sure, this answer is a little late. ;-) Had the some problem but i fortuitous found a quiet simple solution using the Launch Screen.storyboard created with the app automatic.
Open the App-Settings and there App Icons and Launch Images
Select Launch Screen.storyboard in the DropDown-List, even when u think, this is already selected. The display of the screen won´t change after selecting. But when restart the project, the Launch Screen was showed!
BTW to test this tidy, u can set a breakpont in the last line of
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
After trying every other answer here, I finally deleted the LaunchScreen.Storyboard file and created a new one. This was the only thing that fixed the issue for me.
had the same problem with the launchscreen. As mentioned from Abizern, there is no ViewController allowed. If you had one only deleting this one will not be enough some times. The LaunchScreen file could still have some connections to the ViewController which is not available any more. This is a problem, too.
My fix:
Delete ViewController for LaunchScreen
Removed connections in LaunchScreen.storyboard
Removed app from Device
Reinstall
-> Worked :)
What you are missing is that a launch screen is static! It does not need a controller or anything. A controller will not do anything. For the launch screen you can design the UI only using the interface builder, not via code.
Xcode should generally tell you that, if you try to set a custom controller on the launch screen view it results in an error.
So deleting the LaunchScreen.storyboard + LaunchScreenViewController.swift files and adding a Launch Screen.xib file worked in fixing the launch screen. This makes sense to me since the launch screen should be static and not use code.
However the view is still black after the launch screen. I'll make another SO question for that.
i know it is very late but i want to share how i fixed it, if you are checking on real device then try to delete the app first, restart the handset and then reinstall the app. it will be fixed if you have followed all steps like clearing cache and settings in Target - General Tab etc.
In my case, the project navigator file filter was set to "recent". See bottom left of Xcode. I unselected recent, and the file showed up.
Easiest solution is to uninstall and reinstall the app when testing in the simulator. No need to remove and re-create LaunchScreen.Storyboard.

Error message '_BSMachError: (os/kern) invalid capability (20)'

Please note that this error message is pretty low level, so it crops up for different reasons in different scenarios. If you have a scenario that isn't mentioned in one of the answers below, please consider adding your situation as well, so maybe this could be a central answer for various situations that raise this error message.
Edit Nov 10, 2015 Also note, I marked my own answer as the answer, but that was before anyone else had posted. I guess none should really be marked as the answer, because as we've now seen below... this error doesn't have just one answer because it's so low level.
I'm running
iOS 9.0 Simulator
XCode 7.0
Everything was working fine yesterday.
Today, after a bunch of work on rotation related stuff, I started getting this error in my console output when I run the app in the Simulator and I rotate it.
_BSMachError: (os/kern) invalid capability (20)
_BSMachError: (os/kern) invalid name (15)
- I've cleared my build folder,
- I've cleaned the derived data folder,
- I've reset the simulator.
I was working with
UIViewController viewWillLayoutSubviews
UIViewController viewWillTransitionToSize:...
I was also checking various 'Drawing' settings on the Attributes Inspector in IB.
I also made a utility category on UIView where I created a bunch of methods that create CGRect's and helps me assign frames to views.
Based on the https://forums.developer.apple.com/thread/15683:
Change "Localization native development region" in info.plist to United States instead of en.
Updated: Then you can revert these changes back.
I also ran into the _BSMachError console errors while deep linking into the Settings app on iOS 9 from a UIAlertController action. A dispatch_async solved my problem:
[aAlertVC addAction:[UIAlertAction actionWithTitle:#"Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
});
}]];
Ok, I haven't pinned it down completely, but this will get you 99% of the way there.
I'm using a third party map control from ESRI, and something about it doesn't like one of these drawing settings in the Attributes Inspector. I haven't tried each setting individually to see which setting it is, but when I turned all of them off (in the red box), everything worked like a charm, and I quit getting the error message above in the console. If and when I get time to nail it down to the precise setting or combination of settings, i'll update the answer.
It's crazy but for me the solution was just to remove all breakpoints in the file where the error occured.
As for the cause? I think I accidentally hit a shortcut key to create a breakpoint in the current line. Because that was unintended I hit the same shortcut key again to delete it.
Oh my dear XCode...
I was getting the same errors...
_BSMachError: (os/kern) invalid capability (20)
_BSMachError: (os/kern) invalid name (15)
I was calling openURL() from a UIAlertAction
alert.addAction(UIAlertAction(title: actionTitle, style: .Default) {
UIApplication.shared.openURL(url)
}
Deferring execution of the block until the next run loop fixed it...
alert.addAction(UIAlertAction(title: actionTitle, style: .Default) {
OperationQueue.main.addOperation {UIApplication.shared.openURL(url)}
}
I was getting the following when supplying new data:
> _BSMachError: (os/kern) invalid capability (20)
> _BSMachError: (os/kern) invalid name (15)
The error occurred when a button was used to supply new data. An NSTimer was used to refresh and update data upon returning from a performSegueWithIdentifier action. The timer was being activated and then invalidated immediately after use at return time. The MSMachError stopped when the timer was removed and - (void)viewWillAppear:(BOOL)animated and (void)viewDidAppear:(BOOL)animated were employed to perform the same function. This error started with upgrade to Xcode 7.
I got this issue fixed by changing value of Localization native development region key to United Kingdom [or any Specific region] from its default value en present in info.plist of your project.
Select Project Navigator
Locate info.plist file present in ProjectNameTests folder.
Change value of Localization native development region key to any specific region for eg. United Kingdom
I also ran into the same problem in an NSOperation running on a background thread and I was still getting this error because a UIAlertController was still removing itself as another UI transaction was trying to take place. Modifying my code to this fixed the issue.
defer {
dispatch_async( dispatch_get_main_queue(),{
completion()
})
}
A lot of people don't know about defer -It lets the current scope complete and then runs after. Kinda neat.
I did face the same error invalid capability (20) & invalid name (15). I tried the solutions as mentioned by others such as:
Localisation native development region key in info.plist
Changing drawing settings in the Attributes Inspector
Even altered ATS Exception Dictionary in info.plist
But none of those solutions solved my problem.
Actually, I was trying to share some document but generating document would take some time and wanted to display an UIActivityIndicatorView to the user till the time document loads.
The solution for my error was:
//Create a alertView add UIActivityIndicatorView to it and present it in ViewController
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//Call method 1 todo background process like getting data
dispatch_sync(dispatch_get_main_queue(), ^{
//Call method 2 to update the UI
[alert dismissViewControllerAnimated:YES completion:^(void){
//My mistake was: I was calling method 2 over here to update the UI
return;
}];
});
});
Changing localization string from en to United States fixed this for me. However, make sure you clean after you change Info.plist. I've noticed that updates don't work when you just build after making plist changes.
In my case it was Little Snitch, it was blocking urls automatically.
I could reproduce the error for me:
If a make changes to one of the Views within a View that I am actually closing already (popViewControllerAnimated) I receive the error.
I am having a UINavigationButton action that makes an asynchronous task (POSTRequest).
Before performing this request I set the customView of that button to an progress indicator.
When coming back from the asynchronous call I dispatch to the main thread and reset the customView of that button.
After that I am closing the view (popViewControllerAnimated).
This is the CORRECT code where the error does not appear:
/* right way, working without BSMachError */
#IBAction func sendRequest(sender: UIBarButtonItem) {
/* setting the progress indicator as customView of the self.saveButton */
self.showActivityIndicatory(self.saveButton)
/* asynchronous REST call */
UserDataManager.sharedInstance.requestFeedback(request, onCompletion: { error in
dispatch_async(dispatch_get_main_queue(),{
/* resetting the saveButton again to default by setting customView to nil */
self.saveButton.customView = nil
/* closing the view */
self.navigationController!.popViewControllerAnimated(true)
})
})
}
What caused the error was switching lines: closing the view and then setting the customView to nil:
/* WRONG way, causing BSMachError */
#IBAction func sendRequest(sender: UIBarButtonItem) {
/* setting the progress indicator as customView of the self.saveButton */
self.showActivityIndicatory(self.saveButton)
/* asynchronous REST call */
UserDataManager.sharedInstance.requestFeedback(request, onCompletion: { error in
dispatch_async(dispatch_get_main_queue(),{
/* closing the view */
self.navigationController!.popViewControllerAnimated(true)
/* resetting the saveButton again to default by setting customView to nil */
self.saveButton.customView = nil
})
})
}
This error started popping up after I added some observers:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillHideOrShow(_:)), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.keyboardWillHideOrShow(_:)), name:UIKeyboardWillHideNotification, object: nil)
The problem went away when I specified the class name instead of self:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyClass.keyboardWillHideOrShow(_:)), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyClass.keyboardWillHideOrShow(_:)), name:UIKeyboardWillHideNotification, object: nil)
I had the same error and none of the above applied to my problem. The problem appeared when I registered my view controller as an observer to a device orientation change, so the views could be resized and the drawings in the view could be made according to the new size of the view.
I had an outlet of a viewGraph which was a subclass of UIView in which I drew some graphics.In landscape mode the size of the viewGraph is larger than in portrait mode. So when the device changes its orientation the speedGraph needed to be redrawn.
The problem was, that I added several subviews to the speedGraph view, that contained graphics. These subviews needed to be laid out anew in the speedGraph view and then be redrawn. After the device changed its orientation I called viewDidAppear again to make the speedGraph view and all its subviews to be laid out anew and redraw themselves. Calling setNeedsDisplay for speedGraph doesn't work with orientation changes and subviews in a view.
What did I do wrong that caused the error to appear. In viewDidAppear I call a method which does some calculations and adds the subviews to the speedGraph view. The problem was that these subviews were created in the method and were added to the speedGraph view in this method. After leaving the method, the references to these subviews are, of course, deleted, but the subviews in the speedGraph view remain, since they are added. When the device changes, the subviews are created again and added to the speedGraph view, that already has these subviews, but can't find the references to these subviews anymore. The array of subviews of speedGraph view gets longer and longer with (i think) dangling subviews.
I solved the problem by defining the subviews that will be added to the speedGraph view as a class property and then do what needed to be done with the views inside this method. With this change the problem was gone.
Since we can post all situations returning the same error here, I felt free to post mine :). I got the Error when I changed privacy settings in the background. My app opened the settings app so the user can grant it permission to its photolibrary, when the permission switch is set, the app crashes with the mensioned error:
_BSMachError: (os/kern) invalid capability (20)
_BSMachError: (os/kern) invalid name (15)
This appears to be a forced restart of your app by the OS, because the user changed what your app can acces. So in my case it is an action of the OS who caused the error.
I got the same error message, because I assign a object property like #property (assign, nonatomic) NSNumber *aVariable;, fixed by changing to strong.
For what it's worth - it seems that a lot of situations throw this error. In my case, I had posted an alert when the user was dismissing a data entry form and data was in the form. I was able to eliminate the error by programmatically resigning the first responder from all applicable fields before unwinding the view controller.
I saw this when I pressed the Home button while a UIAlertController was displayed, which was dismissed when I relaunched the app. I added code to dismiss the UIAlertController in the appDelegate:
func applicationWillResignActive(application: UIApplication) {
window?.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
}
and the error message disappeared.
I had this error when dismissing a popover via delegate. In the delegateMethod I triggered some GUI-Stuff.
Putting the GUI-Stuff in the completionBlock of dismissViewControllerAnimated fixed it.
[myPopoverView dismissViewControllerAnimated:YES completion:^{ //GUI-Stuff}];
I am a newb at this so take this for what it is worth.
What fixed this for me was changing the Simulated Metrics > Size > to iPad Full Screen. All of my views EXCEPT for the one that threw this error we set to iPad Full Screen. When I changed it, the error went away...
The reason some developers doesn't get the error came back after changing from "Unites States" to "en" (or) other region, is that there is discrepancy between "Property list" and "Source code" views. It's probably Xcode bug. Whenever there is mismatch between these two views will throw this error, whatever it is "en" or "English". If you changed to "en" or "United States" for both views to be the same, will fix the issue.
I got this error from:
var promptsArr = StartRegAlerts() //Instance of the class
etc
func textFieldDidBeginEditing(textField: UITextField) {
switch textField.tag {
case 0:
alert(promptsArr.prompts["Name"]!)
case 1:
alert(promptsArr.prompts["CellPhone"]!)
case 4:
alert2(promptsArr.prompts["NUMBERCORRECT"]!)
//alert(promptsArr.prompts["Wait4Pin"]!)
default: break
}
It only occurred for case 0 but not the other cases:
As a work around for now I commented out case 0 and that stopped the error.
I then changed calling promptsArr.prompts by:
creating a new dictionary prompt and:
override func viewDidAppear(animated: Bool) {
prompt = promptsArr.prompts //
}
and then used prompt in my alert calls. That fixed the problem.
So it appears that it is a timing issue.
with Xcode 8.1 and iOs 10 I also faced
_BSMachError: (os/kern) invalid capability (20)
_BSMachError: (os/kern) invalid name (15)
trying to override UiTraiCollection var to change at runtime the iPad’size classes to have two different interface layouts in Portraid and Landscape. It worked without any crash but generate our errors.
This was the "maliciuos" code:
override public var traitCollection: UITraitCollection {
if UIDevice.currentDevice().userInterfaceIdiom == .Pad && UIDevice.currentDevice().orientation.isPortrait.boolValue {
return UITraitCollection(traitsFromCollections:[UITraitCollection(horizontalSizeClass: .Compact), UITraitCollection(verticalSizeClass: .Regular)])
}
return super.traitCollection
}
The errors gone using override func viewWillTransition as alternative to detect interface rotation.
I hope this will be useful to someone
In my case the cause of the error was due to resizing. Built in IB. Anything that can change the size of a text field or similar for example changing line length can lead to this error I believe. In my case I simply had to adjust the text field size to cover all possibilities so it doesn't need to resize the box and conflict with something else.

UI Testing Failure - Neither element nor any descendant has keyboard focus on secureTextField

This is my case:
let passwordSecureTextField = app.secureTextFields["password"]
passwordSecureTextField.tap()
passwordSecureTextField.typeText("wrong_password") //here is an error
UI Testing Failure - Neither element nor any descendant has keyboard focus. Element:
What is wrong? This is working nice for normal textFields, but problem arise only with secureTextFields. Any workarounds?
This issue caused me a world of pain, but I've managed to figure out a proper solution. In the Simulator, make sure I/O -> Keyboard -> Connect hardware keyboard is off.
Recently we found a hack to make solution from accepted answer persistent. To disable Simulator setting: I/O -> Keyboard -> Connect hardware keyboard from command line one should write:
defaults write com.apple.iphonesimulator ConnectHardwareKeyboard 0
It will not affect a simulator which is running - you need to restart simulator or start a new one to make that setting have its effect.
I have written a small extension (Swift) which works perfect for me.
Here is the code:
extension XCTestCase {
func tapElementAndWaitForKeyboardToAppear(element: XCUIElement) {
let keyboard = XCUIApplication().keyboards.element
while (true) {
element.tap()
if keyboard.exists {
break;
}
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.5))
}
}
}
The main idea is to keep tapping an element (text field) before the keyboard is presented.
Stanislav has the right idea.
In a team environment, you need something that will automatically work. I've come up with a fix here on my blog.
Basically you just paste:
UIPasteboard.generalPasteboard().string = "Their password"
let passwordSecureTextField = app.secureTextFields["password"]
passwordSecureTextField.pressForDuration(1.1)
app.menuItems["Paste"].tap()
Another cause of this error is if there is a parent view of the text field in which you are trying to enter text that is set as an accessibility element (view.isAccessibilityElement = true). In this case, XCTest is not able to get a handle on the subview to enter the text and returns the error.
UI Testing Failure - Neither element nor any descendant has keyboard
focus.
It isn't that no element has focus (as you can often see the keyboard up and blinking cursor in the UITextField), it is just that no element it can reach has focus. I ran into this when attempting to enter text in a UISearchBar. The search bar itself is not the text field, when setting it as an accessibility element, access to the underlying UITextField was blocked. To resolve this, searchBar.accessibilityIdentifier = "My Identifier" was set on the UISearchBar however the isAccessibilityElement was not set to true. After this, test code of the form:
app.otherElements["My Identifier"].tap()
app.otherElements["My Identifier"].typeText("sample text")
Works
It occurred with me for many times.
You have to disable Keyboard Hardware and Same Layout as OSX in your Simulator
Hardware/Keyboard (disable all)
After that keyboard software won't dismiss and your tests can type text
In my case this Hardware -> Keyboard -> Connect Hardware Keyboard -> Disable didn't worked for me.
But when I followed
1) Hardware -> Keyboard -> Connect Hardware Keyboard -> Enabled and run the app
2) Hardware -> Keyboard -> Connect Hardware Keyboard -> Disable.
It worked for me
func pasteTextFieldText(app:XCUIApplication, element:XCUIElement, value:String, clearText:Bool) {
// Get the password into the pasteboard buffer
UIPasteboard.generalPasteboard().string = value
// Bring up the popup menu on the password field
element.tap()
if clearText {
element.buttons["Clear text"].tap()
}
element.doubleTap()
// Tap the Paste button to input the password
app.menuItems["Paste"].tap()
}
Use a sleep between launching the app and typing in data in textfields like this:
sleep(2)
In my case I was keeping getting this error every time and only this solution helped my out.
This maybe help: I just add a "tap" action before the error; that´s all :)
[app.textFields[#"theTitle"] tap];
[app.textFields[#"theTitle"] typeText:#"kk"];
Record case however you want, keyboard or without keyboard attached.
But do the following before playing test.
This following option (connect hardware keyboard) should be unchecked while playing test.
[Reposting Bartłomiej Semańczyk's comment as an answer because it solved the problem for me]
I needed to do Simulator > Reset Contents and Settings in the simulator menu bar to make this start working for me.
Works for me:
extension XCUIElement {
func typeTextAlt(_ text: String) {
// Solution for `Neither element nor any descendant has keyboard focus.`
if !(self.value(forKey: "hasKeyboardFocus") as? Bool ?? false) {
XCUIDevice.shared.press(XCUIDevice.Button.home)
XCUIApplication().activate()
}
self.typeText(text)
}
}
I ran into this issue and was able to fix it in my scenario by taking the solution posted by #AlexDenisov and adding it to my pre-actions for run & test.
The above answers solved it for me when running UI tests while the simulator UI is in the foreground (when you could see the changes in the simulator window). However, it did not work when running them in the background (which is how fastlane ran them, for example).
I had to go to Simulator > Device > Erase All Content and Settings...
To be clear, I manually disabled-enabled-disabled the Hardware Keyboard in the Simulator Settings, set defaults write com.apple.iphonesimulator ConnectHardwareKeyboard 0, and then erased content and settings.
Sometime text fields are not implemented as text fields, or they're wrapped into another UI element and not easily accessible.
Here's a work around:
//XCUIApplication().scrollViews.otherElements.staticTexts["Email"] the locator for the element
RegistrationScreenStep1of2.emailTextField.tap()
let keys = app.keys
keys["p"].tap() //type the keys that you need
//If you stored your data somewhere and need to access that string //you can cats your string to an array and then pass the index //number to key[]
let newUserEmail = Array(newPatient.email())
let password = Array(newPatient.password)
//When you cast your string to an array the elements of the array //are Character so you would need to cast them into string otherwise //Xcode will compain.
let keys = app.keys
keys[String(newUserEmail[0])].tap()
keys[String(newUserEmail[1])].tap()
keys[String(newUserEmail[2])].tap()
keys[String(newUserEmail[3])].tap()
keys[String(newUserEmail[4])].tap()
keys[String(newUserEmail[5])].tap()
The following is from a Swift 5.4, SwiftUI app scenario which would fail UI Testing.
app.cells.firstMatch.tap()
// transition from list view to detail view for item
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.typeText("7620") // :FAIL:
Test: Failed to synthesize event: Neither element nor any descendant has keyboard focus.
Solution: Tap Again
A second tap() was found to pass.
app.cells.firstMatch.tap()
// transition from list view to detail view for item
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.typeText("7620") // :PASS:
However, .doubleTap() and tap(withNumberOfTaps: 2, numberOfTouches: 1) would still fail.
Solution: Await TextField Arrival, Then Tap
Sometimes a view transition needs to expressly await the TextEdit arrival. The approach below awaits the arrival of the targeted TextEdit field.
XCTestCase.swift extension:
extension XCTestCase {
func awaitArrival(element: XCUIElement, timeout: TimeInterval) {
let predicate = NSPredicate(format: "exists == 1")
expectation(for: predicate, evaluatedWith: element)
waitForExpectations(timeout: timeout)
}
func awaitDeparture(element: XCUIElement, timeout: TimeInterval) {
let predicate = NSPredicate(format: "exists == 0")
expectation(for: predicate, evaluatedWith: element)
waitForExpectations(timeout: timeout)
}
}
Example use:
app.cells.firstMatch.tap()
// transition from list view to detail view for item
awaitArrival(
element: app.textFields.matching(identifier: "balance_textedit").element,
timeout: 5)
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.typeText("7620") // :PASS:
Solution: waitForExistence, Then Tap
Use the waitForExistence(timeout:) method provided by XCUIElement.
app.cells.firstMatch.tap()
// transition from list view to detail view for item
app.textFields.matching(identifier: "balance_textedit")
.element.waitForExistence(timeout: 5)
app.textFields
.matching(identifier: "balance_textedit")
.element.tap()
app.textFields
.matching(identifier: "balance_textedit")
.element.typeText("7620") // :PASS:
Your first line is just a query definition, which doesn't mean that passwordSecureTextField would actually exist.
Your second line will dynamically execute the query and try to (re)bind the query to UI element. You should put a breakpoint on it and verify that one and only one element is found. Or just use an assert:
XCTAssertFalse(passwordSecureTextField.exists);
Otherwise it looks ok, tap should force keyboard visible and then typeText should just work. Error log should tell you more info.
Don't messed up, There problem caught the reason is you are recorded your testing time your app will connection hardware keyboard while your automatic testing time simulator takes only software keyboard. so for how to fix this issues. Just use software keyboard on your recording time. you can see the magic.
We encountered the same error when setting the accessibilityIdentifier value for a custom view (UIStackView subclass) containing UIControl subviews. In that case XCTest was unable to get the keyboard focus for the descendent elements.
Our solution was simply to remove the accessibilityIdentifier from our parent view and set the accessibilityIdentifier for the subviews through dedicated properties.
Another answer, but for us the problem was the view was too close to another view that a Gesture recognizer on it. We found we needed the view to be at least 20 pixels away (in our case below). Literally 15 didn't work and 20 or more did. This is strange I'll admit, but we had some UITextViews that were working and some that were not and all were under the same parent and identical other positioning (and variable names of course). The keyboard on or off or whatever made no difference. Accessibility showed the fields. We restarted our computers. We did clean builds. Fresh source checkouts.
No Need to turn on/off keyboard in I/O.
Don't use .typeText for secureTextField, just use
app.keys["p"].tap()
app.keys["a"].tap()
app.keys["s"].tap()
app.keys["s"].tap()
Bonus: You get keyboard sound click :)
Finally, I wrote a script which edits the Simulator's .plist file and sets the ConnectHardwareKeyboard property to false for the selected simulator. You heard it right, it changes the property for the specifically selected simulator inside "DevicePreferences" dictionary rather than editing the global property.
First, create a shell script named disable-hardware-keyboard.sh with the following contents. You can place it within "YourProject/xyzUITests/Scripts/".:
echo "Script: Set ConnectHardwareKeyboard to false for given Simulator UDID"
if [[ $1 != *-*-*-*-* ]]; then
echo "Pass device udid as first argument."
exit 1
else
DEVICE_ID=$1
fi
DEVICE_PREFERENCES_VALUE='<dict><key>ConnectHardwareKeyboard</key><false/></dict>'
killall Simulator # kill restart the simulator to make the plist changes picked up
defaults write com.apple.iphonesimulator DevicePreferences -dict-add $DEVICE_ID $DEVICE_PREFERENCES_VALUE
open -a Simulator # IMPORTANT
Now follow these steps to call it with passing the selected simulator's udid as an argument:
Edit your Xcode scheme (or UI tests specific scheme if you have one)
Go to: Test > Pre-actions
Add new script by tapping "+" symbol > "New Run Script Action".
Important: Inside "Provide build settings from" dropdown choose your main app target, not the UI tests target.
Now add the following script in the text area below.
Script inside Test>Pre-actions:
#!/bin/sh
# $PROJECT_DIR is path to your source project. This is provided when we select "Provide build settings from" to "AppTarget"
# $TARGET_DEVICE_IDENTIFIER is the UDID of the selected simulator
sh $PROJECT_DIR/xyzUITests/Scripts/disable-hardware-keyboard.sh $TARGET_DEVICE_IDENTIFIER
# In order to see output of above script, append following with it:
# | tee ~/Desktop/ui-test-scheme-prescript.txt
Time to test it:
Launch simulator
Enable hardware keyboard for it
Run any UI test with keyboard interaction. Observe the simulator restarts and the hardware keyboard is disabled. And the test's keyboard interaction is working fine. :)
Long story short: hardware keyboard input in iOS Simulator seems to broken for a long time.
The thing is that -[UIApplicationSupport _accessibilityHardwareKeyboardActive] private method from com.apple.UIKit.axbundle sometimes returns NO even though it should return YES (when a text input view is firstResponder, and the cursor is blinking, which literally means that the hardware keyboard is active).
Put this code anywhere in the app to make iOS Simulator believe that if Software Keyboard is inactive then the hardware one is active.
#if TARGET_OS_SIMULATOR
__attribute__((constructor))
static void Fix_UIApplicationAccessibility__accessibilityHardwareKeyboardActive(void) {
{
static id observer = nil;
observer = [[NSNotificationCenter defaultCenter] addObserverForName:NSBundleDidLoadNotification
object:nil
queue:nil
usingBlock:^(NSNotification * _Nonnull note) {
NSBundle *bundle = note.object;
if ([bundle.bundleIdentifier isEqualToString:#"com.apple.UIKit.axbundle"]) {
Class cls = objc_lookUpClass("UIApplicationAccessibility");
SEL sel = sel_getUid("_accessibilityHardwareKeyboardActive");
Method m = class_getInstanceMethod(cls, sel);
method_setImplementation(m, imp_implementationWithBlock(^BOOL(UIApplication *app) {
return ![[app valueForKey:#"_accessibilitySoftwareKeyboardActive"] boolValue];
}));
}
}];
}
}
#endif
emailTextField.tap() // add this line before typeText
emailTextField.typeText("your text")
The problem for me was the same as for Ted. Actually if password field gets tapped after login field and hardware KB is on, software keyboard will dismiss itself on second field tap, and it's not specific to UI tests.
After some time messing around with AppleScript, here's what I came up with(improvements are welcome):
tell application "Simulator"
activate
tell application "System Events"
try
tell process "Simulator"
tell menu bar 1
tell menu bar item "Hardware"
tell menu "Hardware"
tell menu item "Keyboard"
tell menu "Keyboard"
set menuItem to menu item "Connect Hardware Keyboard"
tell menu item "Connect Hardware Keyboard"
set checkboxStatus to value of attribute "AXMenuItemMarkChar" of menuItem
if checkboxStatus is equal to "✓" then
click
end if
end tell
end tell
end tell
end tell
end tell
end tell
end tell
on error
tell application "System Preferences"
activate
set securityPane to pane id "com.apple.preference.security"
tell securityPane to reveal anchor "Privacy_Accessibility"
display dialog "Xcode needs Universal access to disable hardware keyboard during tests(otherwise tests may fail because of focus issues)"
end tell
end try
end tell
end tell
Create a script file with code above and add it to necessary targets(probably UI tests target only, you may want to add similar script to your development targets to re-enable HW keyboard during development).
You should add Run Script phase in build phases and use it like this:
osascript Path/To/Script/script_name.applescript
Had the same issue with Securetextfields. The connect hardware option in my Simulator was of, but still ran into the issue. Finally, this worked for me (Swift 3):
let enterPasswordSecureTextField = app.secureTextFields["Enter Password"]
enterPasswordSecureTextField.tap()
enterPasswordSecureTextField.typeText("12345678")
What fixed this problem for me was adding a 1 second sleep:
let textField = app.textFields["identifier"]
textField.tap()
sleep(1)
textField.typeText(text)

Weird animations when changing NavigationItem prompt

I have these ViewControllers added in storyboard:
None is connected with a custom class, everything is from pure storyboard.
Video on iPhone simulator on iOS7
This only happens when using AutoLayout on iOS7.
Anyone else seen this?
Download sample project of problem
I think this problem occurs when view is getting autolayout and setting it size to main screen size. In iOS 7 navigation push animation come before view size is set so we can see that animating. Don't worry it works well in iOS 8.0 and later. For iOS 7.0 you can give size of view in viewDidLoad so it can adjust size before it appears.
Edit 2:
As someone mentionned in the comments, I am unable to reproduce the problem with your sample project. One thing I noticed though, is that your project is configured with a deployment target that is iOS 8.3. Here are the steps to fix that :
Step 1: Select your project in Xcode's Project Navigator.
Step 2: Make sure you select your project in the left column of the project editor and not the target
Step 3: Select the Build Settings tab
Step 4: Modify the iOS Deployment Target to iOS 7.1 or iOS 7.0 depending on which OS you are testing with.
Step 5: Build and run.
Hopefully this will help you out.
Edit:
Step1. Select your UIViewController with the label 14 and in the third tab of the right pane of Xcode, enter a Storyboard ID such as vc14.
Step2. Select your UIViewController with the label 12 and in the same tab, enter a custom class such as ViewController.
Step3. Remove the trigger segue action from your Button and replace it by a #IBAction in ViewController
Step4. Add this code to your #IBAction in ViewController :
#IBAction func push(sender: AnyObject) {
var vc14 = self.storyboard?.instantiateViewControllerWithIdentifier("vc14") as! UIViewController
vc14.view.layoutIfNeeded()
self.navigationController?.pushViewController(vc14, animated: true)
}
Explanation:
The weird animation is occurring because layout has never occurred before the segue pushes the UIViewController in the UINavigationController. iOS 7 didn't protect appropriately against such a scenario by manually calling layoutIfNeeded before entering an animation block and when the layout finally occurs, it triggers implicit animations. In the code sample I have given you, I manually trigger layout before pushing the ViewController on the stack in order to avoid this issue.
i think you Press ⌘T. so the Slow animation is start. Check the all Simulator you Use.
Debug->Slow Animation
I attach Image check it.

Issues with Today Widget extension

I have a Today Widget for my app, however I have been told about an issue with it.
Basically, what seems to be happening (I can't test this for myself) is that the widget will sometimes just display 'unable to load' and other times it will just display with a height of 0.
I can't really see why this is happening. I've tested it out on my device and the simulator for weeks now and have never ran into this issue.
I was wondering if it could possibly be down to the refresh code:
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Perform any setup necessary in order to update the view.
var defaults = NSUserDefaults(suiteName: "group.AffordIt")
var newCheck = defaults.boolForKey("new")
if newCheck == true {
completionHandler(NCUpdateResult.NewData)
} else {
completionHandler(NCUpdateResult.NoData)
}
}
'newCheck' is true whenever something changes within my app that needs to be displayed in the widget.
Does anyone know what the possible causes of these issues are?
"unable to load" message appears if your extension crashes often. You can try to re-enable it by removing and adding the extension again.
Are you using your own view controller and xib instead of using storyboard? If yes, it is probably that you didn't set the preferredContentSize in your view controller.
try to put the following code in the init function of ur view controller:
self.preferredContentSize = CGSizeMake(320, 100);
I have just began the extension programming today so I am not sure is it really helpful for u or not. Here is the result in my own widget:
Press Edit button in today extensions
Remove your extension
Add your extension again.

Resources