简体   繁体   中英

Peer to Peer Connection in IOS swift 4

I need help with this code. I followed a tutorial from 2014 and I have an error with dispatch_async. I am trying to create an app that allows the user to play with other player nearby or peer to peer. I think the code needs to be updated because it has been renamed in swift 4 but I don't know what the new name is.

This is the code

// below is where the code are wrong
        dispatch_async(dispatch_get_main_queue(),{ () -> Void in
        NSNotificationCenter.defaultCenter().postNotificationName("MPC_DidChangeStateNotification",object:nil,userInfo: userInfo)
        })

the full code is in this link https://github.com/javaplanet17/test/blob/master/multipeer it is inside of a func on line 36.

the error list first I got this error

MPCHandler.swift:55:9: 'NSNotificationCenter' has been renamed to 'NotificationCenter'

I pressed fix and renamed it then I got another error

MPCHandler.swift:55:123: Use of unresolved identifier 'userInfo'

I pressed fix and renamed it then I still got an error

MPCHandler.swift:55:45: Cannot call value of non-function type 'NotificationCenter' Replace '()' with ''

Once again I pressed fix and changed it

The code now look like this:

NotificationCenter.defaultCenter.postNotificationName("MPC_DidChangeStateNotification",object:nil,userInfo: userinfo)

Then I updated it to:

dispatch_async(dispatch_get_main_queue(),{ () -> Void in
            NotificationCenter.default.post("MPC_DidChangeStateNotification",object:nil,userInfo: userinfo)
        })

yet I still got an error

MPCHandler.swift:55:121: Extra argument 'userInfo' in call

I have tried to change it into:

DispatchQueue.main.async(execute:{ () -> Void in NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MPC_DidReceiveDataNotification"), object: nil, userInfo: userinfo))
        })

but I still get an error. How do I fix this error?

It worked for me this way might try it out

DispatchQueue.main.async(execute: { _ in
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil, userInfo: userInfo)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM