Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass data from Objective C to Swift?

How do you pass a data object from an Objective C file to a Swift file ?

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    if([[segue identifier] isEqualToString: @"details"]){
    //create the swift file and set the property I want to pass here


    }

}

In the swift view:

import Foundation
import UIKit
import CoreLocation


public class SwiftViewController: UIViewController{

    var passedObject:NPSCustomObject!

    public override func viewDidLoad() {

    }
like image 727
Nathan Avatar asked Dec 01 '22 18:12

Nathan


2 Answers

I prefer to use NotificationCenter:

Objective C to Swift

Objective C

NSDictionary *myData = @{@"data1" : @"value1", @"data2": @"value2"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotificationName" object:nil userInfo:myData];

Swift

NotificationCenter.default.addObserver(forName:NSNotification.Name(rawValue: "myNotificationName"), object:nil, queue:nil, using:yourFunction)

func yourFunction(notification:Notification) -> Void {
 if let extractInfo = notification.userInfo {
             print(" my data: \(extractInfo["data1"])");
        }
    }
like image 106
Victor Santos Avatar answered Dec 03 '22 06:12

Victor Santos


I found a naive way saving data with NSUserDefaults :

Objective-C Class :

NSString *myObjcData = @"from Objective-C";

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:myObjcData forKey:@"data"];
[defaults synchronize];

Swift Class :

let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()

override func viewDidLoad() {

    super.viewDidLoad()

    // Receive data ---> with NSUserdefaults
    let mySwiftData: AnyObject? = prefs.valueForKey("data")
    println("data is \(mySwiftData)")

}

It's not very elegant but I guarantee it works! Hope it helps.

like image 36
mattyU Avatar answered Dec 03 '22 08:12

mattyU