'How to generate Shake Gesture using Swift (XCTest)
I am writing UI Tests using Swift and XCTest for my application, i have to shake the device to get the notifications, can you please tell me how i can generate the shake gesture within code.
Solution 1:[1]
The solution is stupidly simple. All you need to do is to send "com.apple.UIKit.SimulatorShake" Darwin notification. See the example code below:
SimulatorShaker.h
#import <Foundation/Foundation.h>
@interface SimulatorShaker : NSObject
+ (void)performShake;
@end
SimulatorShaker.m
#import "SimulatorShaker.h"
#import "notify.h"
@implementation SimulatorShaker
+ (void)performShake {
notify_post("com.apple.UIKit.SimulatorShake");
}
@end
If you work with the Swift project you'll have to add a bridging header. Usually Xcode suggests creating the bridging header automatically when you add some Objective-C files to the project. See how to set up the header manually in case you don't find the bridging header or experience any issues building a project
Note: the Darwin Notification API is private to 3rd party developers and Apple won't allow such code to be released to App Store. But you won't experience any bother if you use the SimulatorShaker for UI test purposes only.
Solution 2:[2]
Swift 3
override var canBecomeFirstResponder: Bool {
return true
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("Shaked")
}
}
Solution 3:[3]
There is still no support for shake gestures when using XCUITest. I would suggest you do a work around(two finger tap?) if you can OR use a tool like Appium which supports shake.
Solution 4:[4]
Well first you should add the following method to your UIViewController subclass:
override func canBecomeFirstResponder() -> Bool {
return true
}
Next is to add the motionEnded:withEvent: method:
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
print("Shaked")
}
}
Good luck :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ostap4ik |
| Solution 2 | Community |
| Solution 3 | Reedy |
| Solution 4 | Luca Torella |
