从Swift app调用Objective-C方法

时间:2016-09-04 16:05:03

标签: objective-c swift xcode macos

我正在制作Mac应用程序,完全使用Swift。现在,我需要在应用程序中添加一个Objective-C函数,但我无法弄清楚如何。我对Objective-C知之甚少,但我需要将这个pdf制作函数添加到我的应用程序中:

void MyCreatePDFFile (CGRect pageRect, const char *filename)// 1
{
CGContextRef pdfContext;
CFStringRef path;
CFURLRef url;
CFDataRef boxData = NULL;
CFMutableDictionaryRef myDictionary = NULL;
CFMutableDictionaryRef pageDictionary = NULL;

path = CFStringCreateWithCString (NULL, filename, // 2
                            kCFStringEncodingUTF8);
url = CFURLCreateWithFileSystemPath (NULL, path, // 3
                 kCFURLPOSIXPathStyle, 0);
CFRelease (path);
myDictionary = CFDictionaryCreateMutable(NULL, 0,
                    &kCFTypeDictionaryKeyCallBacks,
                    &kCFTypeDictionaryValueCallBacks); // 4
CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File"));
CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name"));
pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary); // 5
CFRelease(myDictionary);
CFRelease(url);
pageDictionary = CFDictionaryCreateMutable(NULL, 0,
                    &kCFTypeDictionaryKeyCallBacks,
                    &kCFTypeDictionaryValueCallBacks); // 6
boxData = CFDataCreate(NULL,(const UInt8 *)&pageRect, sizeof (CGRect));
CFDictionarySetValue(pageDictionary, kCGPDFContextMediaBox, boxData);
CGPDFContextBeginPage (pdfContext, pageDictionary); // 7
myDrawContent (pdfContext);// 8
CGPDFContextEndPage (pdfContext);// 9
CGContextRelease (pdfContext);// 10
CFRelease(pageDictionary); // 11
CFRelease(boxData);
}

(该代码来自Apple's documentation。)

如何将代码桥接到Swift,如何从Swift视图控制器中调用它?

编辑:我使用的是Swift 3和Xcode 8 beta 5.

1 个答案:

答案 0 :(得分:2)

以下是iOS应用的解决方案:

文件 Thing.h

#import <UIKit/UIKit.h>

@interface Thing : NSObject

void MyCreatePDFFile (CGRect pageRect, const char *filename);

@end

文件 Thing.m

#import "Thing.h"

@implementation Thing

void MyCreatePDFFile (CGRect pageRect, const char *filename) {
    // ... your code here ...
}

@end

在桥接标题中:

#import "Thing.h"

现在你的Swift代码可以看到并调用这个函数。