John Ramos John Ramos - 1 year ago 158
Swift Question

Call an Objective-C Method from Swift app

I am making a Mac app, entirely in Swift. Now, I need to add an Objective-C function to the app, but I can't figure out how. I have very little knowledge about Objective-C, but I need to add this pdf-making function to my app:

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
url = CFURLCreateWithFileSystemPath (NULL, path, // 3
kCFURLPOSIXPathStyle, 0);
CFRelease (path);
myDictionary = CFDictionaryCreateMutable(NULL, 0,
&kCFTypeDictionaryValueCallBacks); // 4
CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File"));
CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name"));
pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary); // 5
pageDictionary = CFDictionaryCreateMutable(NULL, 0,
&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

(That code is from Apple's documentation.)

How can I bridge that code to Swift, and how do I call it from my Swift view controller?

Edit: I'm using Swift 3 and Xcode 8 beta 5.

Answer Source

You cannot use your function at all in an OS X (macOS) app, because there is no such thing as CGRect there; you have an iOS function. So here's the solution for an iOS app:

File Thing.h:

#import <UIKit/UIKit.h>

@interface Thing : NSObject

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


File Thing.m:

#import "Thing.h"

@implementation Thing

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


In the bridging header:

#import "Thing.h"

Now your Swift code can see and call this function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download