像百度網盤等應用,裡面的文件打開時,都可以通過以下應用再打開文件。下面紅色框框內的我的jpg就是我做的一個例子。因為例子沒有提供Icon,所以顯示的是默認icon。
下面就是這例子的主要步驟和代碼。vcD4KPHA+Cjxicj4KPC9wPgo8cD4KwP3X08rH0ru49rTyv6pqcGfNvMass8zQ8qGjPC9wPgo8cD4KPGJyPgo8L3A+CjxwPgoxoaLU2s/uxL+1xCoqaW5mby5wbGlzdM7EvP7W0MztvNOjujwvcD4KPHA+CjwvcD4KCgoKPHN0cm9uZz5baHRtbF08L3N0cm9uZz4gdmlldwogcGxhaW5jb3B5PGltZyBzcmM9″/wp-content/images1/20181026/20141029085648116271.png” width=”12″ height=”12″ alt=”在CODE上查看代碼片”>
- CFBundleDocumentTypes
- CFBundleTypeIconFiles
- icon@2x.png
- icon.png
- CFBundleTypeName
- Molecules Structure File
- CFBundleTypeRole
- Viewer
- LSHandlerRank
- Owner
- LSItemContentTypes
- com.fzrong.jpg
- org.gnu.gnu-zip-archive
- UTExportedTypeDeclarations
- UTTypeConformsTo
- public.plain-text
- public.text
- UTTypeDescription
- Molecules Structure File
- UTTypeIdentifier
- com.fzrong.jpg
- UTTypeTagSpecification
- public.filename-extension
- jpg
- public.mime-type
- image/jpg
-
這就是告訴系統,你能打開 jpg這個文件類型。
2、打開到自己的app時,要截取到過來資源的文件路徑:
在Appdelegate裡添加代碼如下:
[objc] view
plaincopy- – (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
- {
- if (url != nil) {
- NSString *path = [url absoluteString];
- NSMutableString *string = [[NSMutableString alloc] initWithString:path];
- if ([path hasPrefix:@”file://”]) {
- [string replaceOccurrencesOfString:@”file://” withString:@”” options:NSCaseInsensitiveSearch range:NSMakeRange(0, path.length)];
- }
- [self.viewController openPng:string];
- }
- return YES;
-
}
要去掉file://文件路徑的頭,要不然找不到資源。
3、在自己的ViewController裡打開jgp顯示:
[objc] view
plaincopy- – (void)openPng:(NSString*)string
- {
- UIImage *image = [[UIImage alloc] initWithContentsOfFile:string];
- float width = image.size.width;
- float height = image.size.height;
- if (width > 320) {
- height = (height/width) * 300;
- width = 300;
- }
- CGRect frame = CGRectMake(0, 20, width, height);
- imageView.frame = frame;
- imageView.image = image;
-
}
打開之後的效果是這樣的:
註意:這都是在真機上演示的。
這裡例子咱們可以擴展,怎麼打開網盤裡的gif圖片啊,還有其他自己自定義的格式也可以。
項目完整代碼已經上傳到:https://download.csdn.net/detail/totogo2010/7460929
或者github: https://github.com/schelling/openFileType
參考:
https://developer.apple.com/library/ios/qa/qa1587/_index.html
https://stackoverflow.com/questions/20869815/open-file-from-local-file-system-with-default-application-ios