如何在swift中通过通知传递多个值

时间:2015-05-19 14:24:57

标签: ios swift notifications

如何通过通知发送号码和字符串......

let mynumber=1;
let mytext="mytext";
NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: ?????????????);

并在接收器中接收值?

func refreshList(notification: NSNotification){
        let receivednumber=??????????
        let receivedString=?????????
    }

6 个答案:

答案 0 :(得分:29)

您可以将它们包装在NSDictionarylet mynumber=1; let mytext="mytext"; let myDict = [ "number": mynumber, "text":mytext] NSNotificationCenter.defaultCenter().postNotificationName("refresh", object:myDict); func refreshList(notification: NSNotification){ let dict = notification.object as! NSDictionary let receivednumber = dict["number"] let receivedString = dict["mytext"] } 或自定义对象中。

例如:

/*!   
 * @method  
 * 
 * @param interfaceName  
 * The name of the Wi-Fi interface.   
 *   
 * @abstract
 * Invoked when the current SSID changes.                                   
 *   
 * @discussion   
 * Use -[CWWiFiClient startMonitoringEventWithType:error:] with the CWEventTypeSSIDDidChange event type   
 * to register for SSID event notifications.    
 * Use -[CWInterface ssidData] or -[CWInterface ssid] to query the current SSID.
 */   
- (void)ssidDidChangeForWiFiInterfaceWithName:(NSString *)interfaceName;

答案 1 :(得分:24)

Xcode 8.3.1•Swift 3.1

extension Notification.Name {
    static let refresh = Notification.Name("refresh")
}
let object: [String: Any] = ["id": 1, "email": "abc@def.com"]
NotificationCenter.default.post(name: .refresh, object: object)
NotificationCenter.default.addObserver(self, selector: #selector(refreshList), name: .refresh, object: nil)

// Swift 4 or later note: add @objc to the selector `@objc func ...`
// don't forget  vvv add an underscore before the view controller method parameter 
func refreshList(_ notification: Notification) {
    if let object = notification.object as? [String: Any] {
        if let id = object["id"] as? Int {
            print(id)
        }
        if let email = object["email"] as? String {
            print(email)
        }
    }
}

答案 2 :(得分:14)

您可以使用userInfo的{​​{1}}属性:

Notification

并检索:

NotificationCenter.default.post(name: Notification.Name("refresh"),
                                object: nil,
                                userInfo: ["number":yourNumber, "string":yourString])

答案 3 :(得分:4)

实际上有很多方法可以做到这一点。其中之一是传递一组对象,如:

Author
.findOne(2)
.populate('articles')
.exec(function (err, itemPost){
    // some error handling
    async.map(itemPost.articles,
        function (article, callback){
            Article
            .findOne(article.id)
            .populateAll()
            .exec(function (errArticles, articleItem){
                if(errArticles){return callback(errArticles)};
                callback(null, articleItem);
            });
        },
        function (errFromIterator, results){
            if(errFromIterator){res.serverError()};

            var itemPostToJSON = itemPost.toJSON();

            itemPostToJSON.comments = results;

            var clone = _.clone(itemPostToJSON);

            res.send(clone);
        }
    )
});

答案 4 :(得分:2)

Swift 4.0

首先为多个值创建字典。

let name = "Abhi"
let age = 21
let email = "abhi@xyz.com"
let myDict = [ "name": name, "age":age, "email":email]
// post myDict
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "post"), object: nil, userInfo: myDict)

在其他ViewController中添加观察者

NotificationCenter.default.addObserver(self, selector: #selector(doThisWhenNotify(notification:)), name: NSNotification.Name(rawValue: "post"), object: nil)

func doThisWhenNotify(notification : NSNotification) {
    let info = notification.userInfo
    print("name : ",info["name"])
    print("age : ",info["age"])
    print("email : ",info["email"])

}

答案 5 :(得分:1)

Swift 4.0,我传递单键:值,你可以添加多个键和值。


    import { router as authRoutes } from 'routes';

添加观察者和方法定义。您还需要删除观察者。

   NotificationCenter.default.post(name:NSNotification.Name(rawValue: "updateLocation"), object: ["location":"India"])