Qt for ios 打开图片和 office文件
前言
近些年雖然 Qt 對移動開發做了很大的支持,特別是Qt Quick,做移動界面開發非常快捷和方便,但是還是有些平臺性的功能不支持,比如今天要提到的打開文件功能,之前有寫過在 Android 中調用第三方軟件打開本地文件的功能,文章在這里,其實當時也是為了能在 Qt 中調用,而 Qt for ios 中要調用 IOS 代碼進行文件打開功能的調用,這就很麻煩了,因為實在是對 IOS 平臺開發不熟悉,好在在Qt 官網的bug 報告中找到了實現該功能的代碼。這里做個總結,以供后來的人參考。
正文
IOS 在打開 office 文件或圖片時,會默認調用系統功能直接打開該文件,那如果該文件是一個未知文件,那么打開時會自動調起本地已安裝的程序,讓用戶選擇以什么方式打開。
OK,我們先開看看打開文件的代碼,可以直接加到 Qt 工程中去,object-c的源文件是一個 .mm格式文件,頭文件和 C++一樣,都是.h文件。
DocViewController.h
#import <UIKit/UIKit.h> @interface DocViewController : UIViewController <UIDocumentInteractionControllerDelegate> @endDocViewController.mm
#import "DocViewController.h" @interface DocViewController () @end @implementation DocViewController #pragma mark - #pragma mark View Life Cycle - (void)viewDidLoad {[super viewDidLoad]; } #pragma mark - #pragma mark Document Interaction Controller Delegate Methods - (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {//return [[[[UIApplication sharedApplication]windows] firstObject]rootViewController];return self; } - (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller {[self removeFromParentViewController]; } @end接下來需要定義一個 Qt 可以直接調用的接口,作為 Qt 和 Object-c的連接。
iosLauncher.h
#ifndef IOSLAUNCHER_H #define IOSLAUNCHER_H #include <QString> bool iosLaunchFile(QString strFilePath);#endif // IOSLAUNCHER_HiosLauncher.mm
#include "iosLauncher.h" #include "DocViewController.h" #include <QString> #import <UIKit/UIDocumentInteractionController.h>bool iosLaunchFile(QString strFilePath) {NSString* url = strFilePath.toNSString();NSLog(url);NSURL* fileURL = [NSURL fileURLWithPath:url];static DocViewController* mtv = nil;if(mtv!=nil){[mtv removeFromParentViewController];[mtv release];}UIDocumentInteractionController* documentInteractionController = nil;documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];UIViewController* rootv = [[[[UIApplication sharedApplication]windows] firstObject]rootViewController];if(rootv!=nil){mtv = [[DocViewController alloc] init];[rootv addChildViewController:mtv];documentInteractionController.delegate = mtv;[documentInteractionController presentPreviewAnimated:NO];return true;}return false; }OK,代碼寫完了, 接下來在 Qt 代碼中需要調用的地方,先導入頭文件iosLauncher.h,然后就可以直接調用iosLaunchFile接口了,該接口直接傳入文件路徑即可。
以上示例已經在IOS12真機中驗證通過。
最后,還是希望 Qt 今后能提供平臺性的打開文件功能,這樣就不用這么折騰了,特別是對于這種平臺開發了解甚少的童鞋會有很大的便利性。
參考文章:https://bugreports.qt.io/browse/QTBUG-42942
總結
以上是生活随笔為你收集整理的Qt for ios 打开图片和 office文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2015 error LNK201
- 下一篇: Qt for ios 打开相机(添加权限