I'm having trouble with the setMaximized() method on OSX,
When I invoke it:
Scene scene = new Scene(debug);
stage.setOnCloseRequest(event -> System.exit(0));
stage.setScene(scene);
stage.setMaximized(true);
stage.show();
The app window vanishes.
For clarification I am trying to run the app from Eclipse on OSX 10.9.5.
The same logic seems to work fine on Windows.
Are there any known issues that could cause this? I don't really want to go into writing platform specific implementations of my window.
EDIT: Here is the entire class:
public class Main extends Application {
/** Pane that is used for outputting debug information about touch interactions and user interface elements. */
private DebugParent debug;
private Control customPane;
private Stage stage;
#Override
public void start(Stage stage) throws Exception {
Font.loadFont(this.getClass().getResourceAsStream("/ui/fonts/titillium.otf"), 20);
customPane = FXMLLoader.load(this.getClass().getResource("/ui/Main.fxml"), null, new CustomBuilderFactory());
customPane.dragProcessingModeProperty().set(EventProcessingMode.HANDLER);
// Init Debug
debug = new DebugParent(customPane);
debug.registerCustomPane(customPane);
debug.setOverlayVisible(false);
// Init menu
ContextMenu menu = new MainMenu(catalog, customPane);
customPane.setContextMenu(menu);
// Init scene
Scene scene = new Scene(debug);
this.stage = stage;
this.stage.setOnCloseRequest(event -> System.exit(0));
this.stage.setScene(scene);
this.stage.setMaximized(true);
this.stage.show();
this.stage.addEventHandler(KeyEvent.KEY_PRESSED, this::handleKey);
// Invalidate
customPane.invalidate();
customPane.requestFocus();
}
private void handleKey(KeyEvent keyEvent) {
switch (keyEvent.getCode()) {
case F10: stage.setMaximized(!stage.isMaximized()); break;
case F11: stage.setFullScreen(!stage.isFullScreen()); break;
}
}
public static void main(String[] args) {
launch(args);
}
}
Notably I've found that attempting to enter actual fullscreen mode from here crashes Java altogether.
2015-05-06 21:33:14.795 java[9119:507] *** Assertion failure in -[_NSWindowFullScreenTransition makeAndSetupOverlayWindow], /SourceCache/AppKit/AppKit-1265.21/AppKit.subproj/NSWindowFullScreenTransition.m:776
2015-05-06 21:33:14.799 java[9119:507] An uncaught exception was raised
2015-05-06 21:33:14.799 java[9119:507] Invalid parameter not satisfying: _transitionedWindowBeforeContents != nil
2015-05-06 21:33:14.799 java[9119:507] (
0 CoreFoundation 0x00007fff909e125c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff93d6be75 objc_exception_throw + 43
2 CoreFoundation 0x00007fff909e1038 +[NSException raise:format:arguments:] + 104
3 Foundation 0x00007fff949f43d1 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 189
4 AppKit 0x00007fff91425068 -[_NSFullScreenTransition makeAndSetupOverlayWindow] + 267
5 AppKit 0x00007fff90e4f060 -[_NSFullScreenTransition enterFullScreenTransitionWithOptions:animated:activatingIt:] + 933
6 AppKit 0x00007fff90e4e48e -[NSWindow _enterFullScreenMode:animating:activating:] + 291
7 libglass.dylib 0x00000001204d0c99 -[GlassViewDelegate enterFullscreenWithAnimate:withKeepRatio:withHideCursor:] + 153
8 libglass.dylib 0x00000001204cc606 Java_com_sun_glass_ui_mac_MacView__1enterFullscreen + 358
9 ??? 0x0000000109281954 0x0 + 4448590164
10 ??? 0x0000000109273420 0x0 + 4448531488
11 ??? 0x0000000109273420 0x0 + 4448531488
12 ??? 0x0000000109273c4d 0x0 + 4448533581
)
2015-05-06 21:33:14.800 java[9119:507] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: _transitionedWindowBeforeContents != nil'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff909e125c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff93d6be75 objc_exception_throw + 43
2 CoreFoundation 0x00007fff909e1038 +[NSException raise:format:arguments:] + 104
3 Foundation 0x00007fff949f43d1 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 189
4 AppKit 0x00007fff91425068 -[_NSFullScreenTransition makeAndSetupOverlayWindow] + 267
5 AppKit 0x00007fff90e4f060 -[_NSFullScreenTransition enterFullScreenTransitionWithOptions:animated:activatingIt:] + 933
6 AppKit 0x00007fff90e4e48e -[NSWindow _enterFullScreenMode:animating:activating:] + 291
7 libglass.dylib 0x00000001204d0c99 -[GlassViewDelegate enterFullscreenWithAnimate:withKeepRatio:withHideCursor:] + 153
8 libglass.dylib 0x00000001204cc606 Java_com_sun_glass_ui_mac_MacView__1enterFullscreen + 358
9 ??? 0x0000000109281954 0x0 + 4448590164
10 ??? 0x0000000109273420 0x0 + 4448531488
11 ??? 0x0000000109273420 0x0 + 4448531488
12 ??? 0x0000000109273c4d 0x0 + 4448533581
)
libc++abi.dylib: terminating with uncaught exception of type NSException
By the looks of it JavaFX is not playing nice with OSX animations.
I don't know why setMaximized() didn't work on OS X but
here are some work around that work's:
you can try to get VisualBounds width and height and use that.
Scene scene = stage.getScene();
Screen primaryScreen = Screen.getPrimary();
Rectangle2D visualBounds = primaryScreen.getVisualBounds();
double width = visualBounds.getWidth();
double height = visualBounds.getHeight();
scene = new Scene(root, width, height);
Related
I'm having an issue where our application is crashing when the user taps the profile picture to upload their photo to the app. The app sends an authorization request to the user, and this crash happens immediantly once the "allow" button is tapped.
Maybe relevant information is that this is not the root view controller. The registration process has a series of pages on the same Storyboard. This is occuring on any page where I need to request permissions that isn't the main root controller.
I have attempted to place the PhotoAuthorization block of code into a DispatchQueue.main.async, but that didn't seem to work. This is legacy code by a former developer, so I'm still working on fixing up some stuff.
Code block suspected of crashing the app:
func checkPermission() {
let photoAuthStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthStatus {
case .authorized:
self.showPhotoActionSheet()
case .notDetermined:
PHPhotoLibrary.requestAuthorization({ (newStatus) in
if newStatus == PHAuthorizationStatus.authorized {
self.showPhotoActionSheet()
}
})
case .restricted:
showPermissionRequestReason()
case .denied:
showPermissionRequestReason()
}
}
func showPhotoActionSheet() {
let actionSheet = YoutubeActionController()
actionSheet.addAction(Action(ActionData(title: "Take Photo", image: UIImage(named: "ic_photo_camera")!), style: .default, handler: { action in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
self.imagePicker.sourceType = .camera
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}))
actionSheet.addAction(Action(ActionData(title: "Choose from Camera Roll", image: UIImage(named: "ic_photo_album")!), style: .default, handler: { action in
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
self.imagePicker.sourceType = .savedPhotosAlbum
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}))
actionSheet.addAction(Action(ActionData(title: "Cancel", image: UIImage(named: "ic_cancel")!), style: .cancel, handler: nil))
present(actionSheet, animated: true, completion: nil)
}
Find the traceback below. Any help is greatly appreciated!
2020-01-23 13:39:23.878772+0000 ***[89799:17598462] *** Assertion failure in -[FBSSerialQueue assertOnQueue], /BuildRoot/Library/Caches/com.apple.xbs/Sources/FrontBoardServices_Sim/FrontBoard-626.2/FrontBoardServices/FBSSerialQueue.m:98
2020-01-23 13:39:23.990535+0000 ***[89799:17598462] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'threading violation: expected the main thread'
*** First throw call stack:
(
0 CoreFoundation 0x0000000115f7102e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x0000000115ddeb20 objc_exception_throw + 48
2 CoreFoundation 0x0000000115f70da8 +[NSException raise:format:arguments:] + 88
3 Foundation 0x000000010f613b61 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 191
4 FrontBoardServices 0x000000011c344a8b -[FBSSerialQueue assertOnQueue] + 236
5 FrontBoardServices 0x000000011c2f77b9 -[FBSSceneImpl updateClientSettings:withTransitionContext:] + 70
6 FrontBoardServices 0x000000011c2f7a04 -[FBSSceneImpl updateClientSettingsWithTransitionBlock:] + 154
7 FrontBoardServices 0x000000011c2f7929 -[FBSSceneImpl updateClientSettingsWithBlock:] + 110
8 UIKitCore 0x00000001200c7aa0 -[FBSScene(UIApp) updateUIClientSettingsWithBlock:] + 160
9 UIKitCore 0x000000011fcbf5f6 -[_UISystemAppearanceManager updateScreenEdgesDeferringSystemGestures] + 374
10 UIKitCore 0x000000011ff229e2 __70-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystemGestures]_block_invoke_2 + 118
11 UIKitCore 0x000000011ff00cb5 -[UIViewController _updateSystemAppearanceWithRecursionBlock:action:] + 295
12 UIKitCore 0x000000011ff22629 -[UIViewController _setPresentedStatusBarViewController:] + 220
13 UIKitCore 0x000000011ff129c3 -[UIViewController _presentViewController:modalSourceViewController:presentationController:animationController:interactionController:completion:] + 1381
14 UIKitCore 0x000000011ff143c6 -[UIViewController _presentViewController:withAnimationController:completion:] + 4349
15 UIKitCore 0x000000011ff16c47 __63-[UIViewController _presentViewController:animated:completion:]_block_invoke + 98
16 UIKitCore 0x000000011ff1715f -[UIViewController _performCoordinatedPresentOrDismiss:animated:] + 511
17 UIKitCore 0x000000011ff16ba5 -[UIViewController _presentViewController:animated:completion:] + 187
18 UIKitCore 0x000000011ff16e0c -[UIViewController presentViewController:animated:completion:] + 150
19 *** 0x000000010dc472ca $s14***26RegistrationViewControllerC20showPhotoActionSheetyyF + 2522
20 *** 0x000000010dc462b9 $s14***26RegistrationViewControllerC15checkPermissionyyFySo21PHAuthorizationStatusVcfU_ + 201
21 *** 0x000000010dc46355 $sSo21PHAuthorizationStatusVIegy_ABIeyBy_TR + 53
22 Photos 0x0000000116a72643 __39+[PHPhotoLibrary requestAuthorization:]_block_invoke + 52
23 AssetsLibraryServices 0x000000013927ff7e __79-[PLPrivacy _isPhotosAccessAllowedWithScope:forceHandler:accessAllowedHandler:]_block_invoke.14 + 501
24 AssetsLibraryServices 0x000000013924b60c __pl_dispatch_async_block_invoke + 25
25 libdispatch.dylib 0x0000000117a02848 _dispatch_call_block_and_release + 12
26 libdispatch.dylib 0x0000000117a037b9 _dispatch_client_callout + 8
27 libdispatch.dylib 0x0000000117a09526 _dispatch_lane_serial_drain + 707
28 libdispatch.dylib 0x0000000117a09f5c _dispatch_lane_invoke + 388
29 libdispatch.dylib 0x0000000117a13ff9 _dispatch_workloop_worker_thread + 626
30 libsystem_pthread.dylib 0x00007fff51bfd611 _pthread_wqthread + 421
31 libsystem_pthread.dylib 0x00007fff51bfd3fd start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
The error tells you want to do:
reason: 'threading violation: expected the main thread'
Many times, when you pass a closure, you could be called back on a background thread. But, if you want to do anything with the UI, that must be done on the main thread. We use DispatchQueue.main.async to pass a block to the main queue and have it run on the main thread asynchronously,
In
PHPhotoLibrary.requestAuthorization({ (newStatus) in
if newStatus == PHAuthorizationStatus.authorized {
self.showPhotoActionSheet()
}
})
You need to dispatch to the main thread
PHPhotoLibrary.requestAuthorization({ (newStatus) in
if newStatus == PHAuthorizationStatus.authorized {
DispatchQueue.main.async {
self.showPhotoActionSheet()
}
}
})
It looks like you might be calling checkPermission on the background. If so, you also need to wrap the call to:
self.showPhotoActionSheet()
From the call stack -- it looks like this might be the one you are having problems with.
Whenever View switches to another View, the error says that it is adding script message handler with name "jsHandler" when one already exists? Do I have to check existing name and then add it? How can I check? I find nothing in documentation. I tried with ModalView, too.
Here is ContentView
struct ContentView: View {
#State var counter: Int = 0
var body: some View {
NavigationView{
WebViewController(filePath: "index.html")
.navigationBarTitle(Text("Title"))
.navigationBarItems(trailing:
NavigationLink(destination: Text("Another View")) {
Text("Next")
}
)
}
}
}
Here is WebViewController.
import SwiftUI
import WebKit
struct WebViewController: UIViewRepresentable {
let filePath: String
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.configuration.userContentController.add(ContentController(), name: "jsHandler")
let bundleURL = Bundle.main.resourceURL!.absoluteURL
let html = bundleURL.appendingPathComponent(filePath)
uiView.loadFileURL(html, allowingReadAccessTo:bundleURL)
}
class ContentController: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "jsHandler"{
print(message.body)
}
}
}
}
Here is Logcat:
2019-11-16 23:45:41.330209+0630 tut1[33510:959393] Simulator user has requested new graphics quality: 10
2019-11-16 23:45:46.236890+0630 tut1[33510:959393] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to add script message handler with name 'jsHandler' when one already exists.'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23baa1ee __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff50864b20 objc_exception_throw + 48
2 CoreFoundation 0x00007fff23baa02c +[NSException raise:format:] + 188
3 WebKit 0x00007fff2d0c49dd -[WKUserContentController addScriptMessageHandler:name:] + 209
4 tut1 0x000000010c36d613 $s4tut117WebViewControllerV12updateUIView_7contextySo05WKWebC0C_7SwiftUI0F20RepresentableContextVyACGtF + 483
5 tut1 0x000000010c36de91 $s4tut117WebViewControllerV7SwiftUI19UIViewRepresentableAadEP06updateG0_7contexty0G4TypeQz_AD0gH7ContextVyxGtFTW + 17
6 SwiftUI 0x00007fff2c5fc341 $s7SwiftUI32PlatformViewRepresentableAdaptor33_19642D833A8FE469B137699ED1426762LLV06updateD8Provider_7contexty10UIViewTypeQz_AA0cdE7ContextVyADyxGGtF + 289
7 SwiftUI 0x00007fff2c2653a7 $s7SwiftUI17PlatformViewChild33_A513612C07DFA438E70B9FA90719B40DLLV6update7contexty14AttributeGraph0O7ContextVyADyxGGz_tFyyXEfU_ + 2343
8 SwiftUI 0x00007fff2c25eb86 $s7SwiftUI17PlatformViewChild33_A513612C07DFA438E70B9FA90719B40DLLV6update7contexty14AttributeGraph0O7ContextVyADyxGGz_tF + 310
9 SwiftUI 0x00007fff2c2665d0 $s7SwiftUI17PlatformViewChild33_A513612C07DFA438E70B9FA90719B40DLLVyxG14AttributeGraph07UntypedM0AafGP7_update_5graph9attributeySv_So10AGGraphRefaSo11AGAttributeatFZTW + 32
10 AttributeGraph 0x00007fff2f8f1849 $sTA + 25
11 AttributeGraph 0x00007fff2f8d9255 _ZN2AG5Graph11UpdateStack6updateEv + 1111
12 AttributeGraph 0x00007fff2f8d9513 _ZN2AG5Graph16update_attributeEjb + 377
13 AttributeGraph 0x00007fff2f8de131 _ZN2AG8Subgraph6updateEj + 929
14 SwiftUI 0x00007fff2c10d100 $s7SwiftUI9ViewGraphC14runTransaction33_D63C4EB7F2B205694B6515509E76E98BLL2inySo10AGGraphRefa_tF + 224
15 SwiftUI 0x00007fff2c10d517 $s7SwiftUI9ViewGraphC13updateOutputs2atyAA4TimeV_tFSb5prefs_Sb9idealSizeAC0F0V7outputstSo10AGGraphRefaXEfU_ + 103
16 SwiftUI 0x00007fff2c10d1d1 $s7SwiftUI9ViewGraphC13updateOutputs2atyAA4TimeV_tF + 145
17 SwiftUI 0x00007fff2c4af579 $s7SwiftUI16ViewRendererHostPAAE6render8interval17updateDisplayListySd_SbtFyyXEfU_yyXEfU_ + 1001
18 SwiftUI 0x00007fff2c4aef8a $s7SwiftUI16ViewRendererHostPAAE6render8interval17updateDisplayListySd_SbtFyyXEfU_ + 634
19 SwiftUI 0x00007fff2c4a4274 $s7SwiftUI16ViewRendererHostPAAE6render8interval17updateDisplayListySd_SbtF + 436
20 SwiftUI 0x00007fff2c65a182 $s7SwiftUI14_UIHostingViewC14layoutSubviewsyyF + 226
21 SwiftUI 0x00007fff2c65a1a5 $s7SwiftUI14_UIHostingViewC14layoutSubviewsyyFTo + 21
22 UIKitCore 0x00007fff47a52ad5 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2478
23 QuartzCore 0x00007fff2b06e91d -[CALayer layoutSublayers] + 255
24 QuartzCore 0x00007fff2b073323 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 517
25 QuartzCore 0x00007fff2b07fa7c _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 80
26 QuartzCore 0x00007fff2afc6e54 _ZN2CA7Context18commit_transactionEPNS_11TransactionEd + 324
27 QuartzCore 0x00007fff2affc32f _ZN2CA11Transaction6commitEv + 643
28 SwiftUI 0x00007fff2c65a2a4 $s7SwiftUI14_UIHostingViewC16displayLinkTimer9timestampyAA4TimeV_tF + 228
29 SwiftUI 0x00007fff2c00af7d $s7SwiftUI11DisplayLinkC07displayD5Timer33_D912470A6161D66810B373079EE9F26ALLyySo09CADisplayD0CF + 77
30 SwiftUI 0x00007fff2c00afd6 $s7SwiftUI11DisplayLinkC07displayD5Timer33_D912470A6161D66810B373079EE9F26ALLyySo09CADisplayD0CFTo + 38
31 QuartzCore 0x00007fff2af27b66 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 640
32 QuartzCore 0x00007fff2b000ac3 _ZL22display_timer_callbackP12__CFMachPortPvlS1_ + 299
33 CoreFoundation 0x00007fff23acde8d __CFMachPortPerform + 157
34 CoreFoundation 0x00007fff23b0d9c9 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
35 CoreFoundation 0x00007fff23b0d028 __CFRunLoopDoSource1 + 472
36 CoreFoundation 0x00007fff23b07b64 __CFRunLoopRun + 2516
37 CoreFoundation 0x00007fff23b06e66 CFRunLoopRunSpecific + 438
38 GraphicsServices 0x00007fff38346bb0 GSEventRunModal + 65
39 UIKitCore 0x00007fff47578dd0 UIApplicationMain + 1621
40 tut1 0x000000010c36cc3b main + 75
41 libdyld.dylib 0x00007fff516ecd29 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
I’ve not used SwiftUI before, but I’m guessing that the actions that you’re doing in updateUI, that should happen only once, instead need to be done during makeUIView:
import SwiftUI
import WebKit
struct WebViewController: UIViewRepresentable {
let filePath: String
func makeUIView(context: Context) -> WKWebView {
let uiView = WKWebView()
uiView.configuration.userContentController.add(ContentController(), name: "jsHandler")
let bundleURL = Bundle.main.resourceURL!.absoluteURL
let html = bundleURL.appendingPathComponent(filePath)
uiView.loadFileURL(html, allowingReadAccessTo:bundleURL)
return uiView
}
class ContentController: NSObject, WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "jsHandler"{
print(message.body)
}
}
}
}
I have a crash but I'm not sure what caused it.
I using Twilio framework, and all work fine, but I get a weird prod crash
I look like it a Dictionary related issue:
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000e711dbea8
Crashed: com.apple.root.background-qos
0 libobjc.A.dylib 0x182696654 object_getClass + 64
1 CoreFoundation 0x1833f3e18 _CFRelease + 1060
2 TestApp 0x100cae408 specialized _VariantDictionaryBuffer.nativeUpdateValue(_:forKey:) (TicketsManager.swift)
3 TestApp 0x100b4ba94 specialized ChatManager.getAndJoinDialog(roomId:onSuesscs:onFaild:) (ChatManager.swift:798)
4 TestApp 0x100c5e7f0 specialized ChatMessagesManager.getAllMessagesFromServerForTicket(_:) (ChatMessagesManager.swift:164)
5 TestApp 0x1009d7ca0 ChatViewController.loadAllMessagesFomServer() (ChatViewController.swift:460)
6 TestApp 0x1009feed8 partial apply for closure #1 in ChatViewController.viewWillAppear(_:) (ChatViewController.swift:234)
7 TestApp 0x100aee754 closure #1 in static Utils.performTaskOnMain(_:) (Utils.swift:84)
8 TestApp 0x1009b778c thunk for #callee_owned () -> () (QRCodeViewController.swift)
9 libdispatch.dylib 0x182dcd088 _dispatch_call_block_and_release + 24
10 libdispatch.dylib 0x182dcd048 _dispatch_client_callout + 16
11 libdispatch.dylib 0x182dda378 _dispatch_root_queue_drain + 1028
12 libdispatch.dylib 0x182dd9f10 _dispatch_worker_thread3 + 120
13 libsystem_pthread.dylib 0x183073120 _pthread_wqthread + 1268
14 libsystem_pthread.dylib 0x183072c20 start_wqthread + 4
TicketManager func:
func getAndJoinDialog(roomId : String,onSuesscs: #escaping (() -> Void),onFaild: #escaping (()-> Void)) {
if let channel = self.getDialog(roomId) {
self.addDialog(channel)
self.joinDialogWithBlock(channel, successBlock: onSuesscs, failBlock: { (_) in
onFaild()
})
return
}
self.chat?.channelsList()?.channel(withSidOrUniqueName: roomId, completion: { (result, channel) in
if result.isSuccessful() && channel != nil{
self.addDialog(channel!)
self.joinDialogWithBlock(channel!, successBlock: onSuesscs, failBlock: { (_) in
onFaild()
})
}else {
DDLogError("getAndJoinDialog error: \(String(describing: result.error))")
onFaild()
}
})
} <- **Crash on this line**
add dialog func
func addDialog(_ dialog:TCHChannel)
{
self.dialogs[dialog.sid ?? ""] = dialog
}
I'm not sure what happened that can be caused this crash
I tried to write "Detecting When A User Blows Into The Mic" in Swift and I am receiving this error: "unrecognized selector sent to instance 0x78737d70"
This is my code:
import Foundation
import UIKit
import AVFoundation
import CoreAudio
class ViewController: UIViewController {
// #IBOutlet weak var mainImage: UIImageView!
var recorder: AVAudioRecorder!
var levelTimer = NSTimer()
var lowPassResults: Double = 0.0
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL.fileURLWithPath("dev/null")
//numbers are automatically wrapped into NSNumber objects, so I simplified that to [NSString : NSNumber]
var settings : [NSString : NSNumber] = [AVSampleRateKey: 44100.0, AVFormatIDKey: kAudioFormatAppleLossless, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.Max.rawValue]
var error: NSError?
// mainImage?.image = UIImage(named: "flyForReal.png");
recorder = AVAudioRecorder(URL:url, settings:settings, error:&error)
/*
sending prepareToRecord message -> activate metering -> recording -> NSTimer object that fires once ever 0.03 seconds repeatedly. Every time it fires, it sends a message to the listenForBlow function
*/
if((recorder) != nil){
recorder.prepareToRecord()
recorder.meteringEnabled = true
recorder.record()
levelTimer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: Selector("levelTimerCallback"), userInfo: nil, repeats: true)
}
else{
NSLog("%#", "Error");
}
}
func levelTimerCallback(timer:NSTimer) {
recorder.updateMeters()
let ALPHA: Double = 0.05
var peakPowerForChannel = pow(Double(10), (0.05 * Double(recorder.peakPowerForChannel(0))))
lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
if(lowPassResults > 0.95){
NSLog("#Mic blow detected");
}
NSLog("#Average input: %f Peak input: %f Low pass results: %f", recorder.averagePowerForChannel(0), recorder.peakPowerForChannel(0), lowPassResults);
}
}
I don't know how to fix it. Thanks ahead!
These are the errors I get:
2015-07-05 13:22:11.210 Reaktion[7797:471551] -[Reaktion.ViewController levelTimerCallback]: unrecognized selector sent to instance 0x78737d70
2015-07-05 13:22:11.219 Reaktion[7797:471551] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '- [Reaktion.ViewController levelTimerCallback]: unrecognized selector sent to instance 0x78737d70'
*** First throw call stack:
(
0 CoreFoundation 0x00586746 __exceptionPreprocess + 182
1 libobjc.A.dylib 0x01f87a97 objc_exception_throw + 44
2 CoreFoundation 0x0058e705 -[NSObject(NSObject) doesNotRecognizeSelector:] + 277
3 CoreFoundation 0x004d5287 ___forwarding___ + 1047
4 CoreFoundation 0x004d4e4e _CF_forwarding_prep_0 + 14
5 Foundation 0x0098d6d9 __NSFireTimer + 97
6 CoreFoundation 0x004df866 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 22
7 CoreFoundation 0x004df1ed __CFRunLoopDoTimer + 1309
8 CoreFoundation 0x0049d54a __CFRunLoopRun + 2090
9 CoreFoundation 0x0049ca5b CFRunLoopRunSpecific + 443
10 CoreFoundation 0x0049c88b CFRunLoopRunInMode + 123
11 GraphicsServices 0x03d172c9 GSEventRunModal + 192
12 GraphicsServices 0x03d17106 GSEventRun + 104
13 UIKit 0x00daa106 UIApplicationMain + 1526
14 Reaktion 0x00071034 main + 180
15 libdyld.dylib 0x04911ac9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
the function levelTimerCallback has an argument so the selector must have a colon at the end
selector: "levelTimerCallback:"
the Selector initializer is not needed
I have following code snippets where sometimes this line: self.onPostExecute(transItem) leads to application crash:
func execute(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//Your code to execute in background...
println("Your code to execute in background...")
var transItem:WmTransferItem = self.doInBackground()
dispatch_async(dispatch_get_main_queue(), {
println("code to be executed on the main thread when background task is finished")
self.onPostExecute(transItem) // line 639
});
});
}
What does that mean: with unmangled suffix "_promote0"
Exception:
Thread : Crashed: com.apple.main-thread
0 MyApplication 0x000e9ed8 MyApplication.WmBuildGroupsTask.onPostExecute (MyApplication.WmBuildGroupsTask)(MyApplication.WmTransferItem) -> () (WmBuildGroupsTask.swift:419)
1 libswiftCore.dylib 0x0045803b swift_reportFatalError + 162
2 MyApplication 0x000f2ddc MyApplication.WmBuildGroupsTask.(execute (MyApplication.WmBuildGroupsTask) -> () -> ()).(closure #1).(closure #1) with unmangled suffix "_promote0" (WmBuildGroupsTask.swift:639)
3 MyApplication 0x000f2e34 reabstraction thunk helper from #callee_owned () -> (#unowned ()) to #callee_unowned #objc_block () -> (#unowned ()) (WmBuildGroupsTask.swift)
4 libdispatch.dylib 0x3a133d53 _dispatch_call_block_and_release + 10
5 libdispatch.dylib 0x3a133d3f _dispatch_client_callout + 22
6 libdispatch.dylib 0x3a1366c3 _dispatch_main_queue_callback_4CF + 278
7 CoreFoundation 0x2f47a641 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
8 CoreFoundation 0x2f478f0d __CFRunLoopRun + 1308
9 CoreFoundation 0x2f3e3729 CFRunLoopRunSpecific + 524
10 CoreFoundation 0x2f3e350b CFRunLoopRunInMode + 106
11 GraphicsServices 0x343526d3 GSEventRunModal + 138
12 UIKit 0x31d44871 UIApplicationMain + 1136
13 MyApplication 0x00166417 main (main.m:32)
What I'm doing wrong?
Thanks,
I can't accept this answer as write answer but for now this example works properly and I don't have above mentioned crash in crash reports.
Here we go:
I use custom queue based on bundle name instead dispatch_get_global_queue:
let queue = dispatch_queue_create("<BUNDLE_NAME>", nil)
Example
func execute(){
let queue = dispatch_queue_create("<BUNDLE_NAME>", nil)
dispatch_async(queue, {
//Your code to execute in background...
println("Your code to execute in background...")
var transItem:WmTransferItem = self.doInBackground()
dispatch_async(dispatch_get_main_queue(), {
println("code to be executed on the main thread when background task is finished")
self.onPostExecute(transItem)
});
});
}
Hope it will help to someone.