2015-11-19 5 views
0

Привет, у меня есть проблема с моим приложением. Я добавил приложения 3D Touch Quick, и моя проблема в том, что мое приложение не работает в многозадачном режиме, а затем не открывать листок Share в моем приложении. кто-нибудь идея, как я могу исправить проблему, то есть мой код проблема заключается только в быстром действии share на информационном представлении, а проблема быстрого действия работает нормально.Функция быстрого действия с быстрым действием 3D не работает, когда приложение закрыто

// AppDelegate.swift

импорт UIKit импорт MessageUI

@UIApplicationMain класс AppDelegate: UIResponder, UIApplicationDelegate, MFMailComposeViewControllerDelegate {

var window: UIWindow? 

enum QuickActionType : String { 
    case viewControllerInfo = "com.example.infoView" 
    case share = "com.example.share" 
    case problem = "com.example.problem" 

} 

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    var QuickAction = false 

    if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem{ 
     QuickAction = true 
     handleQuickAction(shortcutItem) 
    } 

    return !QuickAction 

} 

func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { 
    let handledQuickAction = handleQuickAction(shortcutItem) 
    completionHandler(handledQuickAction) 

} 

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { 
    if error != nil { 
     print(error?.localizedDescription) 
    } 

    self.window?.rootViewController?.dismissViewControllerAnimated(true, completion: nil) 

} 


func applicationWillResignActive(application: UIApplication) { 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
} 

func applicationDidEnterBackground(application: UIApplication) { 
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 
} 

func applicationWillEnterForeground(application: UIApplication) { 
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 
} 

func applicationDidBecomeActive(application: UIApplication) { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
} 

func applicationWillTerminate(application: UIApplication) { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 

func handleQuickAction(shortcutItem: UIApplicationShortcutItem) -> Bool { 

    var handled = false 

    if let shortCutType = QuickActionType.init(rawValue: shortcutItem.type){ 
     let rootNavigationViewController = window!.rootViewController as? UINavigationController 
     let rootViewController = rootNavigationViewController?.viewControllers.first as UIViewController? 

     rootNavigationViewController?.popToRootViewControllerAnimated(false) 

     switch shortCutType { 

      // Quick Action Info 

     case .viewControllerInfo: 
      handled = true 
      rootViewController?.performSegueWithIdentifier("infoView", sender: nil) 


     case .share: 
      handled = true 

      let shareItems = ["hello world"] 

      let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil) 

      self.window?.rootViewController?.presentViewController(activityViewController, animated: true, completion: nil) 

      // Quick Action Problem 

     case .problem: 
      handled = true 

      let mailController = MFMailComposeViewController() 
      mailController.mailComposeDelegate = self 
      mailController.setToRecipients(["[email protected]"]) 
      mailController.setSubject("App Bug") 
      mailController.setMessageBody("(Your Problem) 

      self.window?.rootViewController?.presentViewController(mailController, animated: true, completion: nil) 

     } 
    } 

    return handled 

} 

}

+0

Может ли кто-нибудь мне помочь? – chris188

ответ

0

Попробуйте добавить небольшое задержка перед обращением с вашими быстрыми действиями и посмотреть, помогает. Я узнал, когда выполнял свои быстрые действия, чтобы они не работали на 100% надежно без небольшой задержки. В настоящее время я использую 0,5 секунды. Вы можете сделать что-то вроде этого (в Obj-C):

[self.performSelector:@selector(doAction:) withObject:obj afterDelay:0.5]; 

или стрижа:

self.performSelector("doAction:", withObject: obj, afterDelay: 0.5) 

Это может или не может помочь в вашем случае, но он сделал в шахте, и я подал радар на нем, о котором я еще не слышал.

0

Эй, вам нужно показать, что ViewController в верхней части текущего ViewController пытается это сделать. Это простое расширение, например, добавьте его в AppDelegate.

extension UIWindow { 

func visibleViewController() -> UIViewController? { 
    if let rootViewController: UIViewController = self.rootViewController { 
     return UIWindow.getVisibleViewControllerFrom(rootViewController) 
    } 
    return nil 
} 

class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController { 

    if vc.isKindOfClass(UINavigationController.self) { 

     let navigationController = vc as! UINavigationController 
     return UIWindow.getVisibleViewControllerFrom(navigationController.visibleViewController!) 

    } else if vc.isKindOfClass(UITabBarController.self) { 

     let tabBarController = vc as! UITabBarController 
     return UIWindow.getVisibleViewControllerFrom(tabBarController.selectedViewController!) 

    } else { 

     if let presentedViewController = vc.presentedViewController { 

      return UIWindow.getVisibleViewControllerFrom(presentedViewController.presentedViewController!) 

     } else { 

      return vc; 
     } 
    } 
}} 

Прямо сейчас вы можете проверить видимый ViewController как этот

self.window?.visibleViewController()?.presentViewController(yourviewcontroller, animated: true, completion: nil) 

Я надеюсь, что это поможет вам.

+0

isKindOfClass? Ты серьезно? : D Это самый похожий на objc-swift-код, который я видел до сих пор. Откуда вы это узнали? ;) – Ben

+0

Да, как вы можете видеть, он работает, чтобы проверить текущий видимый диспетчер видимости – BilalReffas

+0

Возможно, но стиль кода ужасен – Ben

 Смежные вопросы

  • Нет связанных вопросов^_^