Peer to Peer Connection in IOS swift 4 - ios

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)
})

Related

AVAudion Session Interruption

` setSession()
UIApplication.shared.beginReceivingRemoteControlEvents()
becomeFirstResponder()
NotificationCenter.defaultCenter.addObserver(self, Selector("handleInterruption"), name: AVAudioSessionInterruptionNotification, object: nil)
//the Error is the line above this comment
player = Player()
player.playStream(fileUrl: "http:wwwwww.mp3")
updatePlayButton()`
Im trying to check when a phone call has finished by using AVAudiointerruptionNotification but I'm doing something wrong I keep getting the Argument labels _, _, name, object do not match any available overloads...
The new way of using the Notification center in swift 3 is as fallows. I was able to compile with no errors or warnings!
NotificationCenter.default.addObserver(self, selector:
(Selector("handleInterruption")), name:
NSNotification.Name.AVAudioSessionInterruption, object: nil)

table view not getting refreshed on opening app

When the app is open or in background, I am using notification in appdelegate to update the message box table and then it is working.
Appdelegate (in didFinishLaunchingWithOptions and didReceiveRemoteNotification):
NSNotificationCenter.defaultCenter().postNotificationName("changeMessageBox", object: nil)
MessageViewController:
in viewdidload:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector (MessagesViewController.reloadtable), name: "changeMessageBox", object: nil)
func reloadtable()
{
clearArrays()
if (PFUser.currentUser()!["firebaseUID"] !== nil)
{
self.updateResultArray(PFUser.currentUser()!["firebaseUID"] as! String)
resultsTable.reloadData()
}
}
and data is refreshed in the message box.
But when the app is closed and i recieve a chat, the message box ( the window with messages from all the people not the individual chat) does not get updated.
I have to open the app, go to message box ,then back to main page and go back to message box again only then the table view gets refreshed.
Do you guys know what am i missing?
Try below code for post notification,
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("changeMessageBox", object: nil)
})
I was having same issue and resolved like this. Hope this will help you.
Receiving Notification while app in closed or in suspended state will trigger
application:handleActionWithIdentifier:forRemoteNotification:completionHandler:
Try to post notification in this method. i guess it will update your view.
Additionally Refer this document if you have query with Notifiacation
http://samwize.com/2015/08/07/how-to-handle-remote-notification-with-background-mode-enabled/

how to retrieve the list of your application’s tiles already on the Microsoft Band 1

Im creating a Microsoft Band 1 application for iOS with Swift
This function on the documentation has me going cross eyed. Please help.
I know functions can act as types in Swift
i.e.
var exampleFunction: (String, Int) -> String
is a function that takes two parameters, a string and an int and returns a string.
The method I'm looking at says the following in Xcode (Swift language):
tilesWithCompletionHandler(completionHandler: (([AnyObject]!, NSError!) -> Void)!
which I believe is saying, titlesWithCompletionHandler takes in a parameter which is a function of type [AnyObject]!, NSError!) -> Void I'm not sure about the ()! surrounding the whole thing though I know this is forcing a value out of the optional.. thats hard to understand as well.
on the website for the documentation
it is written in Objective-c which shows this as the method definition:
[self.client.tileManager tilesWithCompletionHandler:^(NSArray *tiles, NSError *error) {
if (error){
// handle error
}}];
what I have attempted is to construct a function that is the type this is asking for:
//I had to create this function to match the parameter that the tilesWithCompletionHandler method required
func errorFunction(tileArray: [AnyObject]!, error: NSError!) -> Void {
print("hello")
if((error) != nil) {
//handle error
print("error was not nil, meaning an error occurred... :(")
}
else {
print("i got here")
self.tileArray = tileArray
}
}
then I created a type and assigned it to this function like so (which fixed the errors Xcode was griping about when I called the method Im trying to use):
let customFunction: (([AnyObject]!, NSError!) -> Void)! = errorFunction
the ()! part around the type still confuses me though
finally I call the function that I'm needing to call to get the tiles and pass in the function I just constructed
myBand.tileManager.tilesWithCompletionHandler( customFunction )
Edit: the error was not related to the problem. The print statements do print now, but I get into the error flow.
Am I going about this the right way?
Also, I'm trying to figure out how to handle the error part of the parameters. Do I need to use a
do {
try //some code I need to figure out what to write
} catch let error as NSError {
//code to handle error
}
There's just a lot going on in this method call for me to fully grasp. Any help would be much appreciated. Thank you for your time!
Your error handling seems to be correct in errorFunction. Just modify the print statement to also print the error object to see what the actual error is.
print("error was not nil, meaning an error occurred... :( \(error)")
You could further look at the error.code and add logic in your app to handle it. MSBErrorTypes.h has a list of possible error code and most likely your code will be in the 300 range.
After Larme's comment I was able to get it working with a closure in Swift.
I'm curious if the method I was using in my question would of worked...
This is what I did after updating my print statement that was suggested as well which let me learn you can print errors this way too! :
myBand.tileManager.tilesWithCompletionHandler( {(tiles:[AnyObject]!, error: NSError!) -> Void in
if((error) != nil) {
//handle error
print("Error in .tilesWithCompletionHandler: \(error)")
}
})
It's just a closure which apparently is equivalent to a block in Objective-c which I didn't really know about before now (the block part that is).
Thanks for the help everyone!

'The UIApplicationDelegate in the iPhone App never called reply()' error all of a sudden

I recently reverted back to a previous version of my app through my Time Capsule backup, and everything is working as it should be with the exception of one thing. When I try to use the watch extension for my app, it never receives a reply from the parent application. I haven't changed any code, but it doesn't work no matter what. Even if I just send an empty request and a simple string back, I get the same error:
The UIApplicationDelegate in the iPhone App never called reply()
This is (the simplified version of) my code:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
WKInterfaceController.openParentApplication(["test": "test"]) { userInfo, error in
println("User Info: \(userInfo)")
println("Error: \(error)")
}
}
Delegate:
func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {
let favouritesArrayDefaults = NSUserDefaults.standardUserDefaults().arrayForKey("favourites")!
if let pfqueryRequest: AnyObject = (userInfo as? [String: AnyObject])?["parkName"] {
} else {
let taskID = beginBackgroundUpdateTask()
reply(["Success": "Success"])
endBackgroundUpdateTask(taskID)
}
}
Anyone have any ideas?
You are supposed to call the watch's reply function immediately. You can't wait until an async function completes. By then the watch has given up and decided the phone isn't going to reply. I can't find the statement to that effect in Apple's docs any more, but I do remember reading it.
Your code does not call the replyBlock in the first if block (before the else). Might that be the code path that you see the error log for?
Figured it out! The line:
let favouritesArrayDefaults = NSUserDefaults.standardUserDefaults().arrayForKey("favourites")!
Would crash if the array was empty. This was the first time I had tried the watch app with an empty array in the main app so that was why it had never occurred before.

Updating to Xcode 7 Beta 5 & Swift 2 produced multiple errors

I updated Xcode to the new Xcode 7 beta 5. In doing so, it converted to Swift 2, but then created even more errors. Right now, I am completely stuck, and don't know what to do, because although all my errors are gone, my app will not work correctly.
My problem is this:
if(self.myOutput3 as? NSObject == true) {
print("IT IS TRUE")
PFUser.logInWithUsernameInBackground(self.myOutput1 as! String, password: "xxx") { (user: PFUser?, error: NSError?) -> Void in
if error == nil {
print("It Worked!")
// self.presentViewController(destViewController, animated: true, completion: nil)
let instillation = PFInstallation.currentInstallation()
instillation["user"] = PFUser.currentUser()
instillation.saveInBackgroundWithBlock(nil)
self.performSegueWithIdentifier("toTimeline", sender: self)
} else {
// self.enterButton.enabled = false
self.errorAlert()
print("Couldn't log in...")
}
}
} else {
print("IT IS FALSE")
self.performSegueWithIdentifier("continueTheSignIn", sender: self)
// self.move()
}
The program will perform the toTimeline segue, but not the continueTheSignIn . I don't see any logical reason that this is not working. Could anyone point me in the right direction?
Also, I am having an error in my messages feature.
cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:cell.textView!.textColor]
This is giving me the error "Cannot assign a value of type '[String : UIColor?]' to a value of type '[String: AnyObject]!'
I was not previously getting this error in Swift / Xcode 6.4, so I don't know how to fix it.
Additionally, once I bypass this to get into my app to see if my other features are working, most of my UITableViews are not displaying any information. One is, however the rest load the correct amount of rows, but display nothing. What could this be? Also, no Parse pictures are being displayed correctly either. These are even more concerning than the other problems...
Here is the picture after I deleted and re added the segue under a diff. name.
Parse wont support the beta version . it needs a full version . I have contacted them based on a similar issue . They said they will update the parse to work with xcode7 once the full version of xcode7 is released.

Resources