在混合语言项目中提取通知用户信息
Posted
技术标签:
【中文标题】在混合语言项目中提取通知用户信息【英文标题】:Extract notification userinfo in a mixed language project 【发布时间】:2014-12-11 11:06:57 【问题描述】:我正在开发一个混合语言项目,在 XCode 6 中结合了 Objective C 和 Swift。
在这个项目中,Singleton (Objective C) 类会发布一个通知,然后 ViewController (Swift) 会收到该通知。
Singleton.h
#import <Foundation/Foundation.h>
NSString *const notificationString = @"notificationString";
@interface Singleton : NSObject
+ (id)sharedSingleton;
- (void)post;
@end
Singleton.m
#import "Singleton.h"
static Singleton *shared = nil;
@implementation Singleton
- (id)init
self = [super init];
if (self)
return self;
#pragma mark - Interface
+ (Singleton *)sharedSingleton
static dispatch_once_t pred;
dispatch_once(&pred, ^
shared = [[Singleton alloc] init];
);
return shared;
- (void)post
char bytes[5] = 5, 7, 9, 1, 3;
NSDictionary *objects = @@"device":[NSData dataWithBytes:bytes length:5], @"step1":[NSNumber numberWithInt:4], @"step2":[NSNumber numberWithInt:7];
[[NSNotificationCenter defaultCenter] postNotificationName:notificationString
object:self
userInfo:objects];
@end
当然,在这个混合语言项目中,桥接头必须正确设置(只需在其中添加#import "Singleton.h"
)
ViewController.swift
import UIKit
class ViewController: UIViewController
let singleton = Singleton.sharedSingleton() as Singleton
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "action:", name: notificationString, object: nil)
singleton.post()
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
// MARK: - Notification
func action(notification: NSNotification)
let userInfo = notification.userInfo as Dictionary<String, String> // things go wrong here?!
let hash = userInfo["device"]
let completed = userInfo["step1"]
let total = userInfo["step2"]
这不会产生编译错误。但是,在运行时,XCode 会报告:
致命错误:字典无法从 Objective-C 桥接
notification.userInfo
包含由NSSTring: NSData
、NSSTring: NSNumber
、NSSTring: NSNumber
构建的 NSDictionary,而此命令 let userInfo = notification.userInfo as Dictionary<String, String>
正在尝试转换为 Dictionary<String, String>
这会导致致命错误吗?
在ViewController.swift
中,我应该怎么做才能“读取”从notification.userInfo
传入、从Singleton.m
发送的NSDictionary?
提前致谢
【问题讨论】:
【参考方案1】:尝试这样做
let userInfo = notification.userInfo as Dictionary<String, AnyObject>
正如您所指出的,userInfo 字典包含 NSData、NSNUmber 的值。
【讨论】:
FWIW,我的代码中有Dictionary<String, AnyObject!>
,但效果也不是很好。 AnyObject
显然不应被标记为可选。以上是关于在混合语言项目中提取通知用户信息的主要内容,如果未能解决你的问题,请参考以下文章
提取用户详细信息的 Oauth-2 身份验证需要 CustomPrincipal 对象