給 APP添加外部文件導入功能

意思就是在其他app點擊分享之類的按鈕時會出現(xiàn) '用xxxx(你的app名字)導入' 然后你就可以吧這個文件導入你的app的沙盒當中.

  1. 修改 info.plist(這里public.data是允許所有文件類型,如果要特定某種類型的文件,如只允許導入PPT, 或者Word文檔, 那么就得添加多個CFBundleTypeName CFBundleTypeRole LSHandlerRank LSItemContentTypes 具體見蘋果API文檔)
 <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeIconFiles</key>
            <array/>
            <key>CFBundleTypeName</key>
            <string>data</string>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
            <key>LSHandlerRank</key>
            <string>Default</string>
            <key>LSItemContentTypes</key>
            <array>
                <string>public.data</string>
            </array>
        </dict>
    </array>
    
  1. APPDelegate.h

獲取到根控制器,執(zhí)行復制到Document文件夾方法
源路徑:url.path

@property (strong, nonatomic) NSURL *sharedURL;

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options
{
    if(url.fileURL){
        self.sharedURL = url;
        UIViewController *vc = self.window.rootViewController;
        if ([vc isKindOfClass:[UINavigationController class]]) {
            UINavigationController * nav = (UINavigationController *)self.window.rootViewController;
            UIViewController *topVC = nav.childViewControllers.firstObject;
            if ([topVC respondsToSelector:@selector(handleSharedFile)]) {
                [topVC performSelectorOnMainThread:@selector(handleSharedFile) withObject:nil waitUntilDone:NO];
            }
        } else {
            if ([vc respondsToSelector:@selector(handleSharedFile)]) {
                [vc performSelectorOnMainThread:@selector(handleSharedFile) withObject:nil waitUntilDone:NO];
            }
        }
    }
}
  1. 根控制器方法(頭文件需要聲明方法)
- (void)handleSharedFile {
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (app.sharedURL != nil) {
        self.sharedURL = [app.sharedURL copy];
        app.sharedURL = nil;
        [self saveSharedFile:self.sharedURL];
    }
}
- (void)saveSharedFile:(NSURL *)url {
    MBProgressHUD *hud = [MBProgressHUD showButtonHUDAddedTo:self.view animated:YES];
    DKFile *file = [[DKFile alloc] init];
    file.fullPath = url.path;
    file.fileName = url.path.lastPathComponent;
    [[DKFileManager sharedInstance] copyItemsOfSelectFiles:@[file] fromStorage:DKFileStorageTypeInternal toStorage:DKFileStorageTypeInternal toPath:[DKFileManager defaultPath:kShareDirectory storage:DKFileStorageTypeInternal] progressHUD:hud complete:^{
        [SVProgressHUD showSuccessWithStatus:@"已保存到 iPhone -> SharedFiles"];
    } failure:^(NSError *errors) {
        
    }];
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容