Qt for ios 打开图片和 office文件

版权声明:支持原创,转载请说明~ https://blog.csdn.net/luoyayun361/article/details/84334712

前言

近些年虽然 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>
@end

DocViewController.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_H

iosLauncher.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

猜你喜欢

转载自blog.csdn.net/luoyayun361/article/details/84334712
今日推荐