【问题标题】:Determine if a copy to UIPasteboard was successful or not确定复制到 UIPasteboard 是否成功
【发布时间】:2014-11-23 03:16:26
【问题描述】:

我正在以编程方式将图像复制到 UIPasteboard,并且我想确定复制是否成功。具体来说,我在 iOS 8 上创建了一个自定义键盘,其中一些键会将图像复制到粘贴板上,供用户粘贴到文本字段中。

UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
[pasteBoard setImage:[UIImage imageNamed:anImage]];

为此,用户必须在键盘上允许“完全访问”。所以我要么必须有办法确定完全访问是否打开(不知道如何检查),要么确定复制到粘贴板是否成功。如果完全访问权限未打开,我必须提醒用户打开它才能使键盘工作。

当复制失败时(由于完全访问关闭),我从 UIPasteboard 收到日志消息:

UIPasteboard - failed to launch pasteboardd. Make sure it's installed in UIKit.framework/Support

有没有办法在运行时捕捉到这个?

任何关于如何实现这一点的建议都将不胜感激!

【问题讨论】:

    标签: ios objective-c ios8 uipasteboard custom-keyboard


    【解决方案1】:

    我现在似乎找到了解决方案。这来自Apple Developer forums (user Andrew Boyd),是我能找到的唯一正确解决问题的帖子。

    - (BOOL)testFullAccess
    {
        NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"yourAppGroupID"];  // Need to setup in Xcode and Developer Portal
        NSString *testFilePath = [[containerURL path] stringByAppendingPathComponent:@"testFullAccess"];
    
        NSError *fileError = nil;
        if ([[NSFileManager defaultManager] fileExistsAtPath:testFilePath]) {
            [[NSFileManager defaultManager] removeItemAtPath:testFilePath error:&fileError];
        }
    
        if (fileError == nil) {
            NSString *testString = @"testing, testing, 1, 2, 3...";
            BOOL success = [[NSFileManager defaultManager] createFileAtPath:testFilePath
                                                               contents: [testString dataUsingEncoding:NSUTF8StringEncoding]
                                                             attributes:nil];
            return success;
        } else {
            return NO;
        }
    }
    

    为此,您必须配置一个应用组,您的键盘扩展程序将使用该组来尝试与您的键盘应用进行通信。为此,请按照 Apple 在Configuring App Groups 上的说明进行操作。使用您在此处创建的标识符替换上述代码中的字符串 yourAppGroupID。然后此方法将尝试与您的键盘的主应用程序进行通信。如果成功,那么我们可以断定完全访问已开启。

    我希望此解决方案对其他人有所帮助,直到 Apple [希望] 添加更快的检查用户是否启用了完全访问权限。更不用说,希望他们为用户创建一种更简单的方式来启用设置菜单之外的完全访问权限。

    【讨论】:

    • 谢谢,蒂姆卡尔森。非常适合我。对于阅读本文的其他人:确保在应用程序和扩展程序目标中都选中了“group.com.yourdomain.yourapp”。 Xcode 6.1 GUI 中的复选框很小,所以很难看到。
    • 这是一个旧答案。检查 iOS8 及以上版本的正确方法是使用 isOpenAccessGranted
    【解决方案2】:

    我正在快速执行此操作:

    func isOpenAccessGranted() -> Bool {
        return UIPasteboard.generalPasteboard().isKindOfClass(UIPasteboard)
    }
    

    也应该在 Obj-C 中工作:

    - (BOOL)isOpenAccessGranted() {
        return [[UIPasteboard generalPasteboard] isKindOfClass:UIPasteboard.class];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      相关资源
      最近更新 更多