2014-09-28 116 views
1

我正在以編程方式將圖像複製到UIPasteboard,並且我想確定複製是否成功。具體來說,我在iOS 8上創建了一個自定義鍵盤,其中一些鍵將圖像複製到粘貼板,供用戶粘貼到文本框中。確定是否向UIPasteboard複製成功

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

要做到這一點,用戶必須允許鍵盤上的「完全訪問」。所以我必須有辦法確定Full Access是否開啓(不知道如何檢查這個),或者確定複製到粘貼板是否成功。如果Full Access未打開,我必須提醒用戶打開它才能使鍵盤正常工作。

當複製不失敗(因爲完全訪問被關閉),我從UIPasteboard獲取日誌消息:

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

反正是有在運行時趕上嗎?

有關如何實現此目的的任何建議,將不勝感激!

回答

3

我似乎已經找到了解決方案。這來自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 [希望]添加一個更快的檢查,如果用戶啓用了Full Access。更不用說,希望他們爲用戶創建一個更簡單的方法來啓用設置菜單之外的完全訪問權限。

+1

謝謝,timgcarlson。爲我完美工作。對於閱讀此內容的其他人:請確保在應用和擴展程序目標中標記了「group.com.yourdomain.yourapp」。該複選框在Xcode 6.1 GUI中非常小巧,所以很難看清楚。 – lifjoy 2014-10-28 19:29:37

+0

這是一箇舊的答案。檢查iOS8及更高版本的正確方法是使用isOpenAccessGranted – 2016-03-15 19:12:35

3

我在SWIFT這樣做:

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

應該在的OBJ-C以及工作:

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