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
                            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);
}

(That code is from Apple’s documentation.)

  • install_name_tool difference between -change and -id
  • Screen capture for iOS
  • iPhone : Best way to detect the end of UIImageView image sequence animation
  • How do I define the size of a CollectionView on rotate
  • Dynamically change cell size according to image in a UICollectionView
  • Error when using imshow on OS X
  • 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.

    Solutions Collect From Internet About “Call an Objective-C Method from Swift app”

    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);
    
    @end
    

    File Thing.m:

    #import "Thing.h"
    
    @implementation Thing
    
    void MyCreatePDFFile (CGRect pageRect, const char *filename) {
        // ... your code here ...
    }
    
    @end
    

    In the bridging header:

    #import "Thing.h"
    

    Now your Swift code can see and call this function.