簡體   English   中英

以編程方式觸發搖動事件iOS

[英]Programmatically trigger shake event iOS

如何在iOS中以編程方式觸發震動事件?

我試過以下但它一直在崩潰......

+ (void)shake {
    NSLog(@"TEST");

    UIMotionEventProxy *m = [[NSClassFromString(@"UIMotionEvent") alloc] _init];

    m->_subtype = UIEventSubtypeMotionShake;
    m->_shakeState = 1;

    [[[UIApplication sharedApplication] keyWindow] motionBegan:UIEventSubtypeMotionShake withEvent:m];
    [[[UIApplication sharedApplication] keyWindow] motionEnded:UIEventSubtypeMotionShake withEvent:m];
}

蘋果在Hardware > Shake Gesture下的模擬器中做了什么?

嘗試更換

UIMotionEventProxy *m = [[NSClassFromString(@"UIMotionEvent") alloc] _init];

UIMotionEventProxy *m = [[UIMotionEventProxy alloc] _init];

NSClassFromString(@"UIMotionEvent")返回nil時,我猜它正在破碎。

您想在越獄應用程序或Apple兼容用途中使用嗎?

對於有關模擬器的問題,Apple使用私有功能。

這是一個小解釋:

當您使用“Shake Gesture”時,模擬器調用sendButtonEvent:0x3fc

sendButtonEvent是Simulator中的一個函數,誰:

  • 獲取frontmostAppPort
  • 通過sendPurpleEvent或HIDEvent發送消息

在越獄應用程序中,您可以執行類似的操作(未經過測試,但應該可以正常工作):

struct UIEvent {
    int subtype;
    double timestamp;
    int type;
} * event;

bzero(event, sizeof(event));

event->type = UIEventTypeMotion;
event->subtype = UIEventSubtypeMotionShake;
event->timestamp = GSCurrentEventTimestamp();

NSString* bundle = [[NSBundle mainBundle] bundleIdentifier];
mach_port_t port = GSCopyPurpleNamedPort([bundle UTF8String]);

GSEventRecord* record = (GSEventRecord*)event;
GSSendEvent(record, port);

更改UIMotionEventProxy類(添加兩個setter方法)似乎可以解決問題。 我只是添加了兩個方法setShakeState_setSubtype ,如下所示。

-(void)setShakeState:(int)fp8 {
    _shakeState = fp8;
}
-(void)_setSubtype:(int)fp8 {
    _subtype = fp8;
}

然后我將代碼更改為以下內容......

UIMotionEventProxy *m = [[NSClassFromString(@"UIMotionEvent") alloc] _init];

[m setShakeState:1];
[m _setSubtype:UIEventSubtypeMotionShake];

[[UIApplication sharedApplication] sendEvent:m];
[[[UIApplication sharedApplication] keyWindow] motionBegan:UIEventSubtypeMotionShake withEvent:m];
[[[UIApplication sharedApplication] keyWindow] motionEnded:UIEventSubtypeMotionShake withEvent:m];

對於模擬器和物理設備來說似乎都能完美運行。 這里是主要的和頭文件提供下載,如果有人想看到完整的UIMotionEventProxy文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM