2015年7月13日 星期一

[Swift] Using Swift Protocol in Objective-C

I have a ListView that is populated with detected device information when my scanning service has successfully scanned nearby devices. My scanning service is in Objective C and my App is in Swift, so I will have to use Swift protocol in Objective C functions.

The goal is simple: when device is found, notify the ListView controller. The ListView controller will then retrieve detected device information and then populate the ListView. Note that in the following snippet I have omitted how to populate data into ListView

If you follow the following steps you should have no problem using Swift protocol in Objective C files.



1. Declare the protocol in Swift, I have decided to create a new file called Delegate.swift for easy maintenance.
1
2
3
4
5
//...
@objc public protocol NotifyScanCompletionDelegate{
    func NotifyScanCompletion()
}
//...

2. Declare swift protocol in objective c header:
1
@property (nonatomic, weak) id<NotifyScanCompletionDelegate> NotifyScanCompletion;

3. Set up the Swift protocol in the function that will be used in Objective C .m file. In my case I wish to emit a signal when I discover a device, I will setup my delegate in the deviceFound function in .m file.
1
2
3
4
5
6
7
8
9
@implementation ScanDeviceClass
//...
//omitted
//...
- (void) deviceFound {
    NSLog(@"deviceWasAdded Callback %s", __PRETTY_FUNCTION__);    
    [self.NotifyScamCompletion NotifyScanCompletion:self];
}
@end
Reminder: don't forget to #import {name}-Swift.h to Objective C .m file

4. Extend the protocol in your Controller class and implement the delegate in the ListViewController.swift. Remember to initialize it.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class deviceListViewController: UITableViewController, UITableViewDelegate, NotifyScanCompletionDelegate {
    var scanService:ScanDeviceClass!
    //.....omitted
    override func viewDidLoad()
    {
        super.viewDidLoad()
        scanService = ScanDeviceClass.getInstance()
        scanService.NotifyScanCompletion = self
        scanService.startScanDiscovery()
         }
    func NotifyScanCompletion(getData: AnyObject?)
    {
        populateDevicesList()
        println(">>>>> delegate successful <<<<<")
    }
    //.....omitted
}

Now I can see a list of devices after scanning is successful, automagically.

沒有留言:

張貼留言