NewbieWantsToMaster NewbieWantsToMaster - 5 months ago 28
iOS Question

swift code not working in Xcode 7 (setCategory, AVFormatIDKey,AVAudioRecorder)

I have a piece of code that was previously working in Xcode 6 but not now in Xcode 7. I have a picture of it here errors

I'm getting 3 errors about "Cannot assign a value", "Cannot invoke
initializer", "Cannot invoke Setcategory",

Also, here is the code, any ideas what am I doing wrong?

Best,

import UIKit
import AVFoundation

class RecordViewController: UIViewController {

required init?(coder aDecoder: NSCoder) {


var baseString : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
self.audioURL = "sound.m4a"
var pathComponents = [baseString, self.audioURL]
var audioNSURL = NSURL.fileURLWithPathComponents(pathComponents)
var session = AVAudioSession.sharedInstance()
session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)

var recordSettings: [NSObject : AnyObject] = Dictionary()
recordSettings[AVFormatIDKey] = kAudioFormatMPEG4AAC
recordSettings[AVSampleRateKey] = 44100.0
recordSettings[AVNumberOfChannelsKey] = 2

self.audioRecorder = AVAudioRecorder(URL: audioNSURL, settings: recordSettings, error: nil)
self.audioRecorder.meteringEnabled = true
self.audioRecorder.prepareToRecord()

super.init(coder: aDecoder)
}


@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var saveButton: UIBarButtonItem!

var audioRecorder : AVAudioRecorder
var audioURL = ""

override func viewDidLoad() {
super.viewDidLoad()

self.playButton.enabled = false
self.saveButton.enabled = false

// Do any additional setup after loading the view.
}

@IBAction func cancelTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}

@IBAction func saveTapped(sender: AnyObject) {
}

@IBAction func recordTapped(sender: AnyObject) {
self.playButton.enabled = true
}

@IBAction func playTapped(sender: AnyObject) {
}


}

Answer

Try this:

do {
       try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch (_) {

}

var recordSettings: [String : AnyObject] = Dictionary()
recordSettings[AVFormatIDKey] = NSNumber(unsignedInt: kAudioFormatMPEG4AAC)
recordSettings[AVSampleRateKey] = 44100.0
recordSettings[AVNumberOfChannelsKey] = 2

self.audioRecorder = AVAudioRecorder()

do {
      self.audioRecorder = try AVAudioRecorder(URL: audioNSURL!, settings: recordSettings)
} catch (_) {

}

Basically, with Swift 2, you need to handle exceptions and type casting little differently.

Comments