Facebook signup uses wrong segue within if statement - Swift - ios

So on my first screen of my iOS app I have a “Login” “SignUp” and a “SignUp With Facebook” buttons. The first two buttons link to their own view controllers just fine, and once logged in the simulator will automatically log them in with the:
if PFUser.currentUser() != nil {
self.performSegueWithIdentifier("autoSegue", sender: self)
} else {
Code that you can see at the bottom of the full block of code below. However the Facebook signup I want to transition to a separate view controller where I can show them their profile pic, capture the data on Parse, have them enter a user name, then segue to the same view controller that the SignUp and Login go to – autoSegue. I have all the code on that view controller already written out, but my problem is that when they click the signup button for Facebook, it takes them through the autoSegue and not the fbSignup segue (the one that links to where I want to capture the FB data). Both segues are linked directly from the view controller (not the buttons themselves), and I receive no build errors. I appreciate any help.
Thanks!
Full code:
import UIKit
import Parse
import MediaPlayer
import FBSDKCoreKit
class ViewController: UIViewController {
#IBOutlet var loginAlpha: UIButton!
#IBOutlet var signupAlpha: UIButton!
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
#IBAction func facebookSignup(sender: AnyObject) {
let permissions = ["public_profile"]
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) { (user: PFUser?, error: NSError?) -> Void in
if let error = error {
print(error)
} else {
if let user = user {
self.performSegueWithIdentifier("fbSignup", sender: self)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// code for background video
let theURL = NSBundle.mainBundle().URLForResource("test", withExtension: "mp4")
avPlayer = AVPlayer(URL: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEnd.None
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = UIColor.clearColor();
view.layer.insertSublayer(avPlayerLayer, atIndex: 0)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "playerItemDidReachEnd:",
name: AVPlayerItemDidPlayToEndTimeNotification,
object: avPlayer.currentItem)
}
func playerItemDidReachEnd(notification: NSNotification) {
let p: AVPlayerItem = notification.object as! AVPlayerItem
p.seekToTime(kCMTimeZero)
}
override func viewDidAppear(animated: Bool) {
if PFUser.currentUser() != nil {
self.performSegueWithIdentifier("autoSegue", sender: self)
} else {
signupAlpha.alpha = 0
loginAlpha.alpha = 0
UIView.animateWithDuration(1.5, delay: 1.0, options: [], animations: { () -> Void in
self.signupAlpha.alpha = 1.0
self.loginAlpha.alpha = 1.0
}, completion: nil)
avPlayer.play()
paused = false
}
}
override func viewDidDisappear(animated: Bool) {
avPlayer.pause()
paused = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

You are using Storyboards? You may have messed up on the storyboard and connected the segue to the wrong ViewController.
I can't see anything particularly wrong with your code.

Related

How to turn off Background Music using a Toggle Switch in Xcode using Swift?

I am playing background music in my app from the App delegate once the app launches. Now, In my 2nd V.C. I have set up a toggle switch to turn om/off the background music. But, whenever I am running the follwing code, my app is crashing giving me this error:-
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Could anyone please let me know how can I implement the following task in my V.C. Would appreciate your help! Thanks:)
**App Delegate**
let vc = SecondViewController()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
vc.playMusic()
return true
}
**Second View Controller**
import UIKit
import AVFoundation
class SecondViewController: UIViewController {
#IBOutlet weak var musicToggleSwitch: UISwitch!
var music: AVAudioPlayer!
let vc_1 = ViewController()
override func viewDidLoad() {
super.viewDidLoad()
self.musicToggleSwitch.setOn(UserDefaults.standard.bool(forKey: "musicToggleState"), animated: true)
}
#IBAction func musicToggleSwitch(_ sender: UISwitch) {
if (musicToggleSwitch.isOn == true) {
if (music.isPlaying == false) {
music.play()
}
}
else {
if (music.isPlaying == true) {
music.stop()
}
}
UserDefaults.standard.set(sender.isOn, forKey: "musicToggleState")
}
func playMusic() {
if let musicURL = Bundle.main.url(forResource: "Music", withExtension: "mp3") {
if let audioPlayer = try? AVAudioPlayer(contentsOf: musicURL) {
music = audioPlayer
music.numberOfLoops = -1
music.play()
}
}
}
}
This should solve your issues.
If it still doesn't play, add some breakpoints in the creation block of the music variable to see what goes wrong.
class SecondViewController: UIViewController {
#IBOutlet weak var musicToggleSwitch: UISwitch!
var music: AVAudioPlayer? = {
guard let musicURL = Bundle.main.url(forResource: "Music", withExtension: "mp3") else {
return nil
}
let audioPlayer = try? AVAudioPlayer(contentsOf: musicURL)
audioPlayer?.numberOfLoops = -1
return audioPlayer
}()
override func viewDidLoad() {
super.viewDidLoad()
self.musicToggleSwitch.setOn(UserDefaults.standard.bool(forKey: "musicToggleState"), animated: true)
}
#IBAction func musicToggleSwitch(_ sender: UISwitch) {
guard let music = music, sender.isOn != music.isPlaying else {
return
}
if sender.isOn {
music.play()
} else {
music.stop()
}
UserDefaults.standard.set(sender.isOn, forKey: "musicToggleState")
}
func playMusic() {
music?.play()
}
}
The problem is this line:
let vc = SecondViewController()
That is not the same SecondViewController that you see in your interface. So playMusic is called on the wrong view controller, and on the view controller you can see music remains nil and you crash.

How to create a function which will add reward on watching an ad video

I have a counter in my game that adds a score by 1, and I want a rewarded video on my game over screen that can boost the player score by 100 but I'm not sure how to execute the function when the ad ends. Here is my code:
// FirstViewController.swift
import UIKit
import Firebase
import AVFoundation
import StoreKit
import GameKit
import Appodeal
class Page1: UIViewController, AVAudioPlayerDelegate, GADInterstitialDelegate, UIAlertViewDelegate, GKGameCenterControllerDelegate, AppodealInterstitialDelegate {
let ncObserver = NotificationCenter.default
let PlayAgainObserver = NotificationCenter.default
let AddScoreObserver = NotificationCenter.default
var player = AVAudioPlayer()
/* Variables */
var gcEnabled = Bool() // Check if the user has Game Center enabled
var gcDefaultLeaderBoard = String() // Check the default leaderboardID
var score = 0
let LEADERBOARD_ID = "ScoreID"
var interstitial: GADInterstitial!
var counter: Int = 0
var counter2: Int = 0
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageControl: UIPageControl!
#IBOutlet weak var placementField: UITextField!
// #IBOutlet weak var testpulse: UIButton!
let notification = NotificationCenter.default
let notification2 = NotificationCenter.default
override func viewDidLoad() {
super.viewDidLoad()
authenticateLocalPlayer()
Appodeal.setInterstitialDelegate(self)
ncObserver.addObserver(self, selector: #selector(self.StopSoundsfunc), name: Notification.Name("StopSounds"), object:nil)
PlayAgainObserver.addObserver(self, selector: #selector(self.PlayAgainfunc), name: Notification.Name("PlayAgain"), object:nil)
AddScoreObserver.addObserver(self, selector: #selector(self.AddScorefunc), name: Notification.Name("AddScore"), object:nil)
interstitial = GADInterstitial(adUnitID: "ca-app-pub-6626761084276338/5899386416")
let request = GADRequest()
interstitial.load(request)
}
#IBAction func playAgain(_ sender: Any) {
if counter % 15 == 0 {
if interstitial.isReady {
interstitial.present(fromRootViewController: self)
interstitial = CreateAd()
} else {
print("Ad wasn't ready")
}
}
counter += 1
}
#objc func PlayAgainfunc(_ sender: Any) {
if counter % 15 == 0 {
if interstitial.isReady {
interstitial.present(fromRootViewController: self)
interstitial = CreateAd()
} else {
print("Ad wasn't ready")
}
}
counter += 1
}
#IBAction func ShowAds(_ sender: Any) {
// notification.post(name: Notification.Name("PlayAgain"), object: nil)
Appodeal.showAd(AppodealShowStyle.interstitial, rootViewController: self)
}
#IBAction func AddScore(_ sender: Any) {
notification.post(name: Notification.Name("AddScore"), object: nil)
}
// MARK: - OPEN GAME CENTER LEADERBOARD
#IBAction func checkGCLeaderboard(_ sender: AnyObject) {
let gcVC = GKGameCenterViewController()
gcVC.gameCenterDelegate = self
gcVC.viewState = .leaderboards
gcVC.leaderboardIdentifier = LEADERBOARD_ID
present(gcVC, animated: true, completion: nil)
}
// MARK: - ADD 10 POINTS TO THE SCORE AND SUBMIT THE UPDATED SCORE TO GAME CENTER
#objc func AddScorefunc(_ sender: AnyObject) {
// Add 1 point to current score
score += 1
// Submit score to GC leaderboard
let bestScoreInt = GKScore(leaderboardIdentifier: LEADERBOARD_ID)
bestScoreInt.value = Int64(score)
GKScore.report([bestScoreInt]) { (error) in
if error != nil {
print(error!.localizedDescription)
} else {
print("Best Score submitted to your Leaderboard!")
}
}
}
// MARK: - AUTHENTICATE LOCAL PLAYER
func authenticateLocalPlayer() {
let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(ViewController, error) -> Void in
if((ViewController) != nil) {
// 1. Show login if player is not logged in
self.present(ViewController!, animated: true, completion: nil)
} else if (localPlayer.isAuthenticated) {
// 2. Player is already authenticated & logged in, load game center
self.gcEnabled = true
// Get the default leaderboard ID
localPlayer.loadDefaultLeaderboardIdentifier(completionHandler: { (leaderboardIdentifer, error) in
if error != nil { print(error)
} else { self.gcDefaultLeaderBoard = leaderboardIdentifer! }
})
} else {
// 3. Game center is not enabled on the users device
self.gcEnabled = false
print("Local player could not be authenticated!")
print(error!)
}
}
}
func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismiss(animated: true, completion: nil)
}
}
func CreateAd() -> GADInterstitial {
let interstitial = GADInterstitial(adUnitID: "ca-app-pub-6626761084276338/5899386416")
interstitial.load(GADRequest())
return interstitial
}
func interstitialDidFailToLoadAd(){
NSLog("Interstitial failed to load")
}
func interstitialDidReceiveAd(_ interstitial: GADInterstitial) {
print("Interstitial adapter class name: \(String(describing: interstitial.adNetworkClassName))")
}
#IBAction func RewardedVideo(_ sender: Any) {
Appodeal.showAd(AppodealShowStyle.rewardedVideo, rootViewController: self)
}
In my "AddScorefunc" I have a counter that increases the score by 1. I want to create a similar function that increases the score by 100 but only if the rewarded video requirements are met.
If we look into the SDK integration guide of AppoDeal, they have provided delegates for all kind of ads you show through their sdk. For your case of showing a rewarded video, the delegate is AppodealRewardedVideoDelegate and here is how you can use it to get the callback and add score.
extension Page1: AppodealRewardedVideoDelegate {
func rewardedVideoDidLoadAd(){
NSLog("video ad was loaded")
}
func rewardedVideoDidFailToLoadAd(){
NSLog("video ad failed to load")
}
func rewardedVideoDidPresent(){
NSLog("video ad was presented");
}
func rewardedVideoWillDismiss(){
NSLog("video ad was closed");
}
func rewardedVideoDidFinish(_ rewardAmount: UInt, name rewardName: String!){
NSLog("video ad was fully watched");
// Add score here i.e, score += 100
}
}
In viewDidLoad of Page1, set the delegate method like this,
override func viewDidLoad() {
super.viewDidLoad()
// set delegate
Appodeal.setRewardedVideoDelegate(self)
}

recording audio in swift and passing the recorded audio to the next view controller

I am trying to record Audio, and pass the recorded audio, to the next view controller. Here is my code for recording Audio
class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
#IBOutlet weak var recording: UILabel!
#IBOutlet weak var recordButton: UIButton!
#IBOutlet weak var stopButton: UIButton!
var audioRecorder:AVAudioRecorder!
var recordedAudio : RecordedAudio!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
// enables record button
// hides the stop button
recordButton.enabled = true
stopButton.hidden = true
}
#IBAction func recordAudio(sender: UIButton) {
//Shows recording label
recording.hidden = false
//diabling record button
recordButton.enabled = false
stopButton.hidden = false
//Filepath Creation
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let currentDateTime = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "ddMMyyyy-HHmmss"
let recordingName = formatter.stringFromDate(currentDateTime)+".wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
println(filePath)
// Recording Session
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
audioRecorder = AVAudioRecorder(URL: filePath, settings: nil, error: nil)
audioRecorder.delegate = self
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
// ToDo create recorded audio file
if(flag)
{ recordedAudio = RecordedAudio()
recordedAudio.filepathURL = recorder.url
recordedAudio.title = recorder.url.lastPathComponent
// ToDo Perform segue
self.performSegueWithIdentifier("stopRecording", sender: recordedAudio)
}
else {
println("Recording was unsuccessfull")
stopButton.hidden = true
recordButton.enabled = true
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue == "stopRecording") {
let PlaySoundsVC:PlaySoundsViewController = segue.destinationViewController as! PlaySoundsViewController
let data = sender as! RecordedAudio
PlaySoundsVC.receivedAudio = data
}
}
#IBAction func stopAudio(sender: UIButton) {
// Hides recording
recording.hidden = true
audioRecorder.stop()
var audioSession = AVAudioSession.sharedInstance()
audioSession.setActive(false, error: nil)
}
}
My Model class is ,
import Foundation
class RecordedAudio : NSObject{
var filepathURL :NSURL!
var title : String!
}
Here is how My second viewcontroller catch the data and uses it,
class PlaySoundsViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
var receivedAudio: RecordedAudio!
func rateplay (rtt : Float32) {
audioPlayer.stop()
audioPlayer.rate = rtt
audioPlayer.currentTime = 0.0
audioPlayer.play()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3")
// {
// // if path is there for mp3
// let filepathurl = NSURL.fileURLWithPath(filePath)
//
// // println(receivedAudio.title)
//
// }
// else {
// println("Path is empty")
//
// }
audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filepathURL, error: nil)
audioPlayer.enableRate = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func playSlow(sender: UIButton) {
// play sloooowllyyyyy
audioPlayer.stop()
audioPlayer.rate = 0.5
audioPlayer.currentTime = 0.0
audioPlayer.play()
}
#IBAction func playFast(sender: UIButton) {
rateplay(1.5)
}
#IBAction func stopAudio(sender: UIButton) {
audioPlayer.stop()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Untill I add the below code,
audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filepathURL, error: nil)
audioPlayer.enableRate = true
I was able to move to the second scene, which means, the audio is successfully recorded. But as soon as i access the data like "receivedAudio.filepathURL" I am getting the error,
fatal error: unexpectedly found nil while unwrapping an Optional value
In the prepareForSegue function of the RecordSoundsViewController you need to write segue.identifier == "stopRecording" as the condition.
Currently you have segue == "stopRecording".
Happy Coding!

Add initial note

I am looking at adding an inital note to the note page within my app. this is so that when people click to the notes part there will be some detail on how to use it rather than just a big empty screen. I have no idea where to implement this though. Could you please help, below is the page where it talks about the dictionaries.
import UIKit
import MessageUI
class DetailViewController: UIViewController, MFMailComposeViewControllerDelegate, UITextViewDelegate {
#IBOutlet weak var tView: UITextView!
#IBAction func BarButton(sender: UIBarButtonItem) {
let textToShare = ""
if let myWebsite = NSURL(string: "")
{
let objectsToShare = [textToShare, myWebsite]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
self.presentViewController(activityVC, animated: true, completion: nil)
}
OpenMail()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tView.text = (allNotes[currentNoteIndex] as Note).note
tView.becomeFirstResponder()
// Set controller as swipe gesture recogniser, to allow keyboard dismissal for text box
var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "dismissKeyboard")
swipe.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(swipe)
self.tView.delegate = self
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if tView.text == "" {
allNotes.removeAtIndex(currentNoteIndex)
}
else {
(allNotes[currentNoteIndex] as Note).note = tView.text
}
Note.saveNotes()
noteTable?.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
// Open mail controller on screen and prepare with preset values.
let mailComposerVC = MFMailComposeViewController()
var MessageText: String!
MessageText = tView.text
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients([""])
mailComposerVC.setSubject("")
mailComposerVC.setMessageBody(MessageText, isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
// Alert user to email error
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate Method
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
func OpenMail() {
//Function to open mail composer on screen
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func dismissKeyboard() {
// Dismiss keyboard for textfield
self.tView.resignFirstResponder()
}
}
note.swift
import UIKit
var allNotes:[Note] = []
var currentNoteIndex:NSInteger = -1
var noteTable:UITableView?
let KAllNotes:String = "notes"
class Note: NSObject {
var date:String
var note:String
override init() {
date = NSDate().description
note = ""
}
func dictionary() -> NSDictionary {
return ["note":note, "date":date]
}
class func saveNotes() {
var aDictionaries:[NSDictionary] = []
for (var i:NSInteger = 0; i < allNotes.count; i++) {
aDictionaries.append(allNotes[i].dictionary())
}
NSUserDefaults.standardUserDefaults().setObject(aDictionaries, forKey: KAllNotes)
// aDictionaries.writeToFile(filePath(), atomically: true)
}
class func loadnotes() {
allNotes.removeAll(keepCapacity: true)
var defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var savedData:[NSDictionary]? = defaults.objectForKey(KAllNotes) as? [NSDictionary]
// var savedData:NSArray? = NSArray(contentsOfFile: filePath())
if let data:[NSDictionary] = savedData {
for (var i:NSInteger = 0; i < data.count; i++) {
var n:Note = Note()
n.setValuesForKeysWithDictionary(data[i] as [NSObject : AnyObject])
allNotes.append(n)
}
}
}
class func filePath() -> String {
var d:[String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if let directories:[String] = d {
var docsDirectory:String = directories[0]
var path:String = docsDirectory.stringByAppendingPathComponent("\(KAllNotes).notes")
return path;
}
return ""
}
}
Thanks in advance
Sam
Add an NSUserDefault boolean that stores whether or not the initial note should be shown, e.g. that the app has been launched for the first time. Then load an initial note accordingly. When a note is added or the initial note is deleted, then change the boolean accordingly so the initial note doesn't show up next time.
You could also initialize your database with an initial note. Not clear from your code how the notes are saved, but this approach would probably rely on the NSUserDefault approach above, except it could be done in the AppDelegate or something.
example:
let InitialSetupComplete = "InitialSetupComplete" // Note: I would define this at the top of a file
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey(InitialSetupComplete) {
// Show initial note
}
// Later on when the note is deleted, or modified (or immediately after initial note loaded into the database, see below)
defaults.setBool(true, forKey: InitialSetupComplete)
Would be easier/cleaner just to initialize your database with the initial note in the app delegate (e.g. call within applicationDidFinishLaunching), so your view controller doesn't have to figure this out. Similar code, except you would use setBool right away after the initial note has been saved to the database. I don't know anything about your database from the question, so can't really provide a more detailed example than this. Hope this helps.

Switch button to mute (swift)

What I am trying to do is have a settings page in my app and when a switch is clicked on (its original state is off) then it will mute the entire app. So far what my code can do is mute only the current view and it works great until I either segue to my main view then that music is still playing that is associated with that and when I segue back to the settings page the mute switch is returned to its original off state and the music is playing once again. I was wondering how to fix my code so that when turned on it mutes all noise. Here is my code thank you for reading and helping:
import UIKit
import AVFoundation
var songs = ""
var backgroundMusicPlayer: AVAudioPlayer!
func playBackgroundMusic(filename: String) {
let url = NSBundle.mainBundle().URLForResource(
filename, withExtension: nil)
if (url == nil) {
println("Could not find file: \(filename)")
return
}
var error: NSError? = nil
backgroundMusicPlayer =
AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil {
println("Could not create audio player: \(error!)")
return
}
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
class settingsView: UIViewController {
#IBOutlet weak var mySwitch: UISwitch!
#IBAction func switchPressed(sender: AnyObject) {
playBackgroundMusic(songs)
if mySwitch.on {
backgroundMusicPlayer.pause()
} else {
backgroundMusicPlayer.play()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
songs = "settingsBackground.mp3"
switchPressed(self)
}
}
You can do it like this way:
MainViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
let status = NSUserDefaults().stringForKey("playerStatus")
if status == "Off"{
if (backgroundMusicPlayer?.playing != nil){
backgroundMusicPlayer?.stop()
}
}else{
songs = "1.mp3"
playBackgroundMusic(songs)
}
}
}
settingsView.swift
import UIKit
class settingsView: UIViewController {
#IBOutlet weak var mySwitch: UISwitch!
#IBAction func switchPressed(sender: AnyObject) {
if mySwitch.on {
NSUserDefaults().setObject("on", forKey: "playerStatus")
playBackgroundMusic(songs)
} else {
NSUserDefaults().setObject("Off", forKey: "playerStatus")
backgroundMusicPlayer!.stop()
}
}
override func viewDidLoad() {
super.viewDidLoad()
let status = NSUserDefaults().stringForKey("playerStatus")
if status == "Off" {
mySwitch.setOn(false, animated: false)
}
}
}
Here is complete working project : https://github.com/DharmeshKheni/Switch-with-AudioPlayer

Resources