FBLoginManager undeclared type - swift

I installed FacebookSDK using Cocoapods, according to Terminal, I have installed FacebookSDK 4.8.0 (CoreKit, ShareKit and LoginKit), I imported the .h files in my BH-File.h, and already initialized everything in my AppDelegate.
For some reason, when trying to log in using a custom button, when I initialize FBLoginManager, I get an error Use of undeclared type "FBLoginManager".
this is my code
if (FBSDKAccessToken.currentAccessToken() == nil)
{
let fbLoginManager : FBSDKLoginManager =
fbLoginManager.logInWithReadPermissions(["public_profile", "email"], fromViewController: self, handler: { (loginResult, error) -> Void in
if error == nil {
print (FBSDKAccessToken.currentAccessToken().tokenString)
}
else {
print ("ERROR*****: \(error)")
}
})
}

What fixed to me was adding import FBSDKCoreKit and FBSDKLoginKit to my class, for some reason is not enough adding it in the BH-file.h

Try something like this, I just checked the code and it works (it's not exactly what you're looking for but I'm sure you can modify it as needed)
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class ProfileViewController: UIViewController,FBSDKLoginButtonDelegate {
// #IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var nextButton: UIButton!
#IBOutlet weak var fbLoginButton: FBSDKLoginButton!
override func viewDidLoad() {
super.viewDidLoad()
self.fbLoginButton.delegate = self
self.fbLoginButton.readPermissions = ["public_profile"]
self.fbLoginButton.publishPermissions = ["publish_actions"]
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "fbProfileChanged:",
name: FBSDKProfileDidChangeNotification,
object: nil)
FBSDKProfile.enableUpdatesOnAccessTokenChange(true)
// If we have a current Facebook access token, force the profile change handler
if ((FBSDKAccessToken.currentAccessToken()) != nil)
{
self.fbProfileChanged(self)
} }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
//facebooks functions
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if (error != nil)
{
print( "\(error.localizedDescription)" )
}
else if (result.isCancelled)
{
// Logged out?
print( "Login Cancelled")
}
else
{
// Logged in?
print( "Logged in, segue now")
self.performSegueWithIdentifier("showHome", sender: self)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
}
//see bitfountain
func fbProfileChanged(sender: AnyObject!) {
let fbProfile = FBSDKProfile.currentProfile()
if (fbProfile != nil)
{
// Fetch & format the profile picture
let strProfilePicURL = fbProfile.imagePathForPictureMode(FBSDKProfilePictureMode.Square, size: imageView.frame.size)
let url = NSURL(string: strProfilePicURL, relativeToURL: NSURL(string: "http://graph.facebook.com/"))
let imageData = NSData(contentsOfURL: url!)
let image = UIImage(data: imageData!)
self.nameLabel.text = fbProfile.name
self.imageView.image = image
self.nameLabel.hidden = false
self.imageView.hidden = false
self.nextButton.hidden = false
}
else
{
self.nameLabel.text = ""
self.imageView.image = UIImage(named: "")
self.nameLabel.hidden = true
self.imageView.hidden = true
}
}
#IBAction func nextButtonPressed(sender: UIButton) {
self.performSegueWithIdentifier("showHome", sender: self)
}
}

Related

Is there a way to throw errors from firebase login to error handling?

I have one class that i call RealTimeAPI and then the actual LoginViewController class and what i want to do is i want to add my register method in my RealtimeApi class and call register in my LoginView. But then i need to errorhandle in my LoginView so i need to throw the error from the completionhandler in the registerfunction RealtimeAPIs Createuser. is this possible or no? this is my code so far.
RealtimeAPIClass
import Foundation
import Firebase
enum RegisterError: Error
{
case IncompleteForm
case NonMatchingForm
case FirebaseError
}
class RealTimeApi
{
private let Reference: DatabaseReference! = Database.database().reference()
private var nilOrNot = [Bool]()
public var errorDescription: String?
func Register(FullName: String?, Username: String?, Email: String?, EmailVerification: String?, Password: String?, PasswordVerification: String? )
{
Auth.auth().createUser(withEmail: Email!, password: Password, completion: er, Error){
}
}
func Login(Username:String, Password: String)
{
}
func CheckLoggedinUser() -> Bool
{
let currentuser = Auth.auth().currentUser
if(currentuser == nil)
{
return false
}else{
return true
}
}
}
Loginview
import UIKit
import Firebase
class LogInV: UIViewController {
#IBOutlet weak var UsernameTxt: UITextField!
#IBOutlet weak var PasswordTxt: UITextField!
#IBOutlet var TextfieldRegistrationCollection: [UITextField]!
#IBOutlet weak var ImageView: UIView!
#IBOutlet weak var RegisterView: UIView!
#IBOutlet weak var RV_VerticalAlignmentConstraint: NSLayoutConstraint!
#IBOutlet weak var RegisterBtnO: UIButton!
var Data = RealTimeApi()
var TextFieldStyle = TextfieldStyling()
override func viewDidLoad() {
super.viewDidLoad()
TextFieldStyle.StylizeTextField(StylizedTextField: UsernameTxt)
TextFieldStyle.StylizeTextField(StylizedTextField: PasswordTxt)
for i in 0...TextfieldRegistrationCollection.count - 1 {
TextFieldStyle.StylizeTextField(StylizedTextField: TextfieldRegistrationCollection[i])
}
TextfieldValidation()
RV_VerticalAlignmentConstraint.constant += view.bounds.height
}
override func viewDidAppear(_ animated: Bool) {
RegisterBtnO.isEnabled = false
}
#IBAction func LoginButtons(_ sender: UIButton) {
switch sender.tag{
case 0:
break
case 1:
Slide()
break
default:
print("button not pressed")
break
}
}
func Slide()
{
UIView.animate(withDuration: 1, delay: 0, options: .curveEaseIn, animations: {
self.RV_VerticalAlignmentConstraint.constant -= self.view.bounds.height
self.view.layoutIfNeeded()
}, completion: nil)
}
#IBAction func RegisterBtn(_ sender: UIButton) {
}
//Validate textfields so that user register does not work for empty input
func TextfieldValidation()
{
for i in 0...TextfieldRegistrationCollection.count - 1
{
TextfieldRegistrationCollection[i].addTarget(self, action: #selector(LogInV.textFieldDidChange), for: UIControlEvents.editingChanged)
}
}
//selector function for controlling empty textfield
#objc func textFieldDidChange(){
var NoneIsEmpty = Int()
for i in 0...TextfieldRegistrationCollection.count - 1{
if let text = TextfieldRegistrationCollection[i].text, text.isEmpty == false {
NoneIsEmpty += 1
}
}
if(NoneIsEmpty == TextfieldRegistrationCollection.count)
{
RegisterBtnO.isEnabled = true
}else{
RegisterBtnO.isEnabled = false
}
NoneIsEmpty = 0
}
func showAlert(error: String)
{
let Erroralert = UIAlertController(title: "Error", message: error, preferredStyle: .alert)
Erroralert.addAction(UIAlertAction(title: "Dissmiss",style: .cancel ,handler: {action in
print("tapped actionbutton")
}))
present(Erroralert, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}
}
func UploadCustomerList(customer: Customer)
{
}
}
So basically i want to do something like this
Auth.auth().createUser(withEmail: Email!, password: Password, completion: User, Error){
throw Error
}
I have created a helper class with the following method:
func setupAlert(with title: String, with message: String?, viewController: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancel = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancel)
viewController.present(alert, animated: true, completion: nil)
}
you must pass the viewcontroller in the parameter where you want to display the alert. Then you can also pass the error, which can be found in Auth.auth()

Recording and playing back audio working on simulator but not on real iPhone device [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 3 years ago.
On the "soundPlayer.play()" line below I get an error:
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value.
However, this only happens when pressing the play button on a real device.
Also please ignore that I named my button "plat" button instead of play button, hah.
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVAudioRecorderDelegate, AVAudioPlayerDelegate {
#IBOutlet weak var recordBTN: UIButton!
#IBOutlet weak var platBTN: UIButton!
var soundRecorder : AVAudioRecorder!
var soundPlayer : AVAudioPlayer!
var fileName: String = "audioFile.m4a"
var player: AVAudioPlayer!
var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
bannerView = GADBannerView(adSize: kGADAdSizeBanner)
addBannerViewToView(bannerView)
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
//ca-app-pub-9351248624194777/2551009478 real
bannerView.rootViewController = self
bannerView.load(GADRequest())
setupRecorder()
platBTN.isEnabled = false
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func setupRecorder() {
let audioFilename = getDocumentsDirectory().appendingPathComponent(fileName)
let recordSetting = [ AVFormatIDKey : kAudioFormatAppleLossless,
AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue,
AVEncoderBitRateKey : 320000,
AVNumberOfChannelsKey : 2,
AVSampleRateKey : 44100.2] as [String : Any]
do {
soundRecorder = try AVAudioRecorder(url: audioFilename, settings: recordSetting )
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
} catch {
print(error)
}
}
func setupPlayer() {
let audioFilename = getDocumentsDirectory().appendingPathComponent(fileName)
do {
soundPlayer = try AVAudioPlayer(contentsOf: audioFilename)
soundPlayer.delegate = self
soundPlayer.prepareToPlay()
soundPlayer.volume = 1.0
} catch {
print(error)
}
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
platBTN.isEnabled = true
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
recordBTN.isEnabled = true
platBTN.setTitle("Play", for: .normal)
}
#IBAction func recordAct(_ sender: UIButton) {
if recordBTN.titleLabel?.text == "Record" {
soundRecorder.record()
recordBTN.setTitle("Stop", for: .normal)
platBTN.isEnabled = false
} else {
soundRecorder.stop()
recordBTN.setTitle("Record", for: .normal)
platBTN.isEnabled = false
}
}
#IBAction func playAct(_ sender: UIButton) {
if platBTN.titleLabel?.text == "Play" {
platBTN.setTitle("Stop", for: .normal)
recordBTN.isEnabled = false
setupPlayer()
soundPlayer.play() //Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
} else {
soundPlayer.stop()
platBTN.setTitle("Play", for: .normal)
recordBTN.isEnabled = false
}
}
#IBAction func playBtnPressed(_ sender: UIButton) {
playSound(soundName: "4chordsong3") //
}
#IBAction func pausePressed(_ sender: UIButton) {
if player?.play() != nil{
player.pause()
}
}
When I press the "play" button, the program immediately crashes and I get the error shown above. Is there any way I can fix this?
I found the solution. I simply added this to the setupRecorder method.:
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSession.Category.playAndRecord)//

How to make a correct authorization

i am making an app Redmine, i have a website with a user with pass and there are issues. But i can't understand what i should do to make authorization.
Here I have Router, Request, AuthViewController. I also wanted to ask how i have to make AuthRequest? What has to be there?
AuthViewController
import UIKit
class AuthViewController: UIViewController {
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var signInBotton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func signInDidTap(_ sender: Any) {
login()
}
fileprivate func login(){
AuthRequest.login(email: emailField.text!, password: passwordField.text!){(user, error) in DispatchQueue.main.async {
[unowned self] in self.openIssues()
}
}
}
}
//extension AuthViewController: Router{
// func prepare() {
// Here error with 'seque' if(seque.identifier = Seque.issues.rawValue){
// print("It's OK")
// guard let controller = seque.destination as? IssuesViewController else { print("Wrong destination"); return}
// //controller.presenter = IssuesPresenter();
// }
// }
//
// func openIssues() {
// print("kek")
// }
//
//
// enum Seque: String {
// case issues = "IssuesSeque"
// }
//
//}
There is also an error in if-block in extension.

Getting data from Parse as “Optional(test)” and want to do something with that “test” part

I am new to Parse and I am trying to retrieve my first password (my password is: test). But I can only receive it as “Optional(test)”. The “test” there is actually the password that I want to receive but I can’t get it out of the paranthesis. My code is as follows;
import UIKit
import Parse
import Bolts
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var userNameTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var credentialsLabel: UILabel!
#IBAction func checkCredentialsButton(sender: AnyObject) {
var query = PFQuery(className:"userName")
query.getObjectInBackgroundWithId("the id of my object") {
(userNameRetrieved: PFObject?, error: NSError?) -> Void in
if error == nil && userNameRetrieved != nil {
println(userNameRetrieved)
println("Username has been retrieved succesfully")
println(userNameRetrieved?.objectForKey("username"))
} else {
println(error)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.userNameTextField.delegate = self
self.passwordTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(userText: UITextField) -> Bool {
userNameTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
return true
}
}
And my logs are as follows;
Optional(<userName: "my username", objectId: “the id that i am using", localId: (null)> {
ACL = "<PFACL: “my acl">";
username = test;
})
Username has been retrieved succesfully
Optional(test)
Is there a way for me to use that password to log my user in?
Also, is there a way for me to retrieve an array of passwords that are registered to check if the password is true or not?
use if let to unwrap the optional
#IBAction func checkCredentialsButton(sender: AnyObject) {
var query = PFQuery(className:"userName")
query.getObjectInBackgroundWithId("the id of my object") {
(userNameRetrieved: PFObject?, error: NSError?) -> Void in
if error == nil && userNameRetrieved != nil {
if error == nil && userNameRetrieved != nil {
if let userArray = userNameRetrieved {
print(userArray)
if let username = userNameRetrieved?.objectForKey("username") {
print(username)
}
}
} else {
println(error)
}
}
}

Crash when repeating a sound with AudioEngine in Swift

I'm trying to play sounds with different effects. In a previous viewController I record a sound, then in the next screen, it can be played with the effects. First time it works ok but the second time it crashes with error as follows:
2015-08-07 13:00:45.900 Pitch Perfect[9643:1121173] 13:00:45.900
ERROR: AVAudioEngine.mm:253: AttachNode: required condition is
false: !nodeimpl->HasEngineImpl() 2015-08-07 13:00:45.953 Pitch
Perfect[9643:1121173] Terminating app due to uncaught exception
'com.apple.coreaudio.avfaudio', reason: 'required condition is false:
!nodeimpl->HasEngineImpl()'
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController, AVAudioPlayerDelegate {
var receivedAudio:RecordedAudio!
var audioPlayer: AVAudioPlayer!
var disabledButton:UIButton!
var firstTime:Bool = true
var audioEngine:AVAudioEngine!
var audioFile:AVAudioFile!
var audioPlayerNode:AVAudioPlayerNode!
var audioStopped:Bool!
var typeOfSound:IntegerLiteralType!
#IBOutlet weak var stopButton: UIButton!
#IBOutlet weak var reverbButton: UIButton!
#IBOutlet weak var echoButton: UIButton!
#IBOutlet weak var darthButton: UIButton!
#IBOutlet weak var chipmonkButton: UIButton!
#IBOutlet weak var snailButton: UIButton!
#IBOutlet weak var rabbitButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filePathUrl, error: nil)
audioPlayer.enableRate=true
audioPlayer.delegate=self
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayback, error: nil)
audioPlayerNode=AVAudioPlayerNode();
audioEngine = AVAudioEngine()
audioFile = AVAudioFile(forReading: receivedAudio.filePathUrl, error: nil)
audioStopped=true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func playAnimalSound(animal: String) {
if audioStopped==false {
resetAudio(typeOfSound)
}
typeOfSound = 1
audioPlayer.currentTime=0
switch animal {
case "snail":
audioPlayer.rate=0.5
case "rabbit":
audioPlayer.rate=2.0
default:
showMessage("Sound not found. How can it be?")
}
audioPlayer.play()
stopButton.hidden=false
stopButton.enabled=true
}
#IBAction func playSnailSound(sender: UIButton) {
highlightButton(sender)
playAnimalSound("snail")
}
#IBAction func playRabbitSound(sender: UIButton) {
highlightButton(sender)
playAnimalSound("rabbit")
}
func soundEnded() {
stopButton.hidden=true
disabledButton.enabled=true;
if(audioEngine.running) {
audioEngine.stop()
audioEngine.reset();
}
}
func playAudioWithVariablePitch(pitch: Float, type: String) {
if audioStopped==false {
resetAudio(typeOfSound)
}
audioEngine.attachNode(audioPlayerNode)
switch type {
case "normal":
typeOfSound = 2
var changePitchEffect = AVAudioUnitTimePitch()
changePitchEffect.pitch = pitch
audioEngine.attachNode(changePitchEffect)
audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil)
audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil)
case "reverb":
typeOfSound = 3
var changeReverbEffect = AVAudioUnitReverb()
changeReverbEffect.loadFactoryPreset(AVAudioUnitReverbPreset(rawValue: 4)!)
changeReverbEffect.wetDryMix=50;
audioEngine.attachNode(changeReverbEffect)
audioEngine.connect(audioPlayerNode, to: changeReverbEffect, format: nil)
audioEngine.connect(changeReverbEffect, to: audioEngine.outputNode, format: nil)
case "delay":
typeOfSound = 3
var changeDelayEffect = AVAudioUnitDelay()
audioEngine.attachNode(changeDelayEffect)
audioEngine.connect(audioPlayerNode, to: changeDelayEffect, format: nil)
audioEngine.connect(changeDelayEffect, to: audioEngine.outputNode, format: nil)
default:
showMessage("oops, there was an internal problem. Never mind")
}
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: soundEnded)
audioEngine.startAndReturnError(nil)
stopButton.hidden=false
stopButton.enabled=true
audioPlayerNode.play()
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
if flag {
stopButton.hidden=true
disabledButton.enabled=true;
audioStopped=true
println("I hid stopButton and enabled the disabled one")
}
}
#IBAction func playDelaySound(sender: UIButton) {
highlightButton(sender)
playAudioWithVariablePitch(0, type: "delay")
}
#IBAction func playReverbSound(sender: UIButton) {
highlightButton(sender)
playAudioWithVariablePitch(0, type: "reverb")
}
#IBAction func playChipmunkSound(sender: UIButton) {
highlightButton(sender)
playAudioWithVariablePitch(1000.0, type: "normal")
}
#IBAction func playDarthVaderSound(sender: UIButton) {
highlightButton(sender)
playAudioWithVariablePitch(-900.0, type: "normal")
}
#IBAction func stopPlaying(sender: UIButton) {
resetAudio(typeOfSound)
stopButton.hidden=true
stopButton.enabled=false;
disabledButton.enabled=true;
}
func highlightButton(button: UIButton) {
if firstTime {
firstTime=false
} else {
disabledButton.enabled=true;
}
button.enabled=false;
disabledButton=button;
}
func resetAudio(type: IntegerLiteralType) {
switch type {
case 1 :
audioPlayer.stop()
println("case 1")
case 2 :
println("case 2")
if audioEngine.running {
audioEngine.stop()
}
audioEngine.reset()
case 3 :
audioEngine.stop()
default:
break
}
audioStopped=true;
}
func showMessage(msg: String) {
var message=UIAlertView(title: "Alert", message: msg, delegate: nil, cancelButtonTitle: "ok I won't panic")
}
}
Does anybody know why it crashes? I have researched the AVAudioEngine, AVAudioPlayer and AVAudioPlayerNode classes with no results.
Thanks
I know this is an old issue, but I didn't see the correct answer above.
The reason why it crashes is actually outlined in the error message:
AttachNode: required condition is false: !nodeimpl->HasEngineImpl()
In other words, when attaching a node it is mandatory that that node is not already attached to an engine (!nodeimpl->HasEngineImpl()).
The solution is to remove the node using audioEngine.detachNode before attempting to add it again.
Finally the crashed was caused by initializing the audioPlayerNode and the audioEngine objects in the viewDidLoad function. They need to be instantiated every time you use them, apparently, or maybe after being stopped and reset.
Placing those lines in the beginning of the playAudioWithVariablePitch function directly instead of in the viewDidLoad function, solved the crash problem. I still have a problem with the playback of the pitched, reverb and echo sounds. They get cut before it's due and I still don't know why. It has to do with the completionHandler of the audioPlayerNode.scheduleFile method.
In my case, my timer was calling again and again and this code was written inside my timer
self.recognitionTask?.finish()
node.removeTap(onBus: 0)
self.request.endAudio()
self.recognitionTask = nil
//Maybe this line was causing the issue
self.audioEngine.stop()
So if you already have stopped the request, removed the tap and stopped the engine, then these lines should not be called again.
Hope this helps some one
It looks like you are resetting the engine after playing the variable pitch effect.
func soundEnded() {
stopButton.hidden=true
disabledButton.enabled=true;
if(audioEngine.running) {
audioEngine.stop()
audioEngine.reset();
}
}
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: soundEnded)
audioEngine.startAndReturnError(nil)
stopButton.hidden=false
stopButton.enabled=true
audioPlayerNode.play()
So the engine hasnt been setup again with the nodes added and the chain linked. When you try to play the playerNode, it crashes.