1. 程式人生 > >Qt for ios 開啟圖片和 office檔案

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>
@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