Swift error : class RecordSoundsViewController has no initializers - xcode

class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate{
#IBOutlet weak var recordButton: UIButton!
#IBOutlet weak var recodinginProgress: UILabel!
#IBOutlet weak var stopButton: UIButton!
var audioPlayer: AVAudioPlayer!
var recordAudio: RecordedAudio!
var audioRecorder:AVAudioRecorder
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) {
//hide the stop button
stopButton.hidden = true
recordButton.enabled = true
}
#IBAction func recordAudio(sender: UIButton) {
recordButton.enabled = false
stopButton.hidden = false
recodinginProgress.hidden = false
//TODO: Record the user"s voice
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)
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()
}
I don't know what I am doing wrong. My error is coming on my class.
It says
class RecordSoundsViewController has no initializers on RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate{

The error message is a bit bad from the compiler. The reason you see the error is because you have a property which does not have a default value.
In Swift all values needs to have a default value unless it's an optional.
In your case it's this property: var audioRecorder:AVAudioRecorder
In your case I would make this property an optional: var audioRecorder:AVAudioRecorder? and make sure to check for nil when using. Or to make it an implicitly unwrapped optional (if you know there's always gonna be a value): var audioRecorder:AVAudioRecorder!

Related

Fatal error editing core data objects

I am newbie to programming. With CoreData, I am trying to create the function to edit the data in input text field to edit the data to be saved to core data. I am having fatal error:
unexpectedly found nil while unwrapping an Optional value
#IBAction func update(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Coursework")
do {
let results = try manageContext.executeFetchRequest(fetchRequest)
let attribute = results[0] as! NSManagedObject
detailItem?.value = modulename.text
attribute.setValue(courseworkname.text, forkey: "courseworkname")
attribute.setValue(dueDateLabel.text, forkey: "duedate")
attribute.setValue(level.text, forkey: "level")
attribute.setValue(mark.text, forkey: "mark")
attribute.setValue(modulename.text, forkey: "modulename")
attribute.setValue(notes.text, forkey: "notes")
attribute.setValue(progressbar.text, forkey: "progressbar")
attribute.setValue(reminder.text, forkey: "reminder")
attribute.setValue(value.text, forkey: "value")
try manageContext.save()
}catch let error as NSError {
}
}
Full code:
#IBOutlet weak var detailDescriptionLabel: UILabel!
#IBOutlet weak var dueDateLabel: UITextField!
#IBOutlet weak var value: UITextField!
#IBOutlet weak var courseworkname: UITextField!
#IBOutlet weak var modulename: UITextField!
#IBOutlet weak var level: UITextField!
#IBOutlet weak var mark: UITextField!
#IBOutlet weak var reminder: UITextField!
#IBOutlet weak var notes: UITextField!
#IBAction func edit(sender: AnyObject) {
modulename.userInteractionEnabled = true
modulename.enabled = true
dueDateLabel.userInteractionEnabled = true
value.userInteractionEnabled = true
modulename.userInteractionEnabled = true
level.userInteractionEnabled = true
mark.userInteractionEnabled = true
reminder.userInteractionEnabled = true
notes.userInteractionEnabled = true
//Interaction
value.enabled = true
dueDateLabel.enabled = true
courseworkname.enabled = true
modulename.enabled = true
level.enabled = true
mark.enabled = true
reminder.enabled = true
notes.enabled = true
}
#IBAction func update(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Coursework")
do {
let results = try manageContext.executeFetchRequest(fetchRequest)
let attribute = results[0] as! NSManagedObject
detailItem?.value = modulename.text
attribute.setValue(courseworkname.text, forKey: "courseworkname")
attribute.setValue(dueDateLabel.text, forKey: "duedate")
attribute.setValue(level.text, forKey: "level")
attribute.setValue(mark.text, forKey: "mark")
attribute.setValue(modulename.text, forKey: "modulename")
attribute.setValue(notes.text, forKey: "notes")
attribute.setValue(progressbar.text, forKey: "progressbar")
attribute.setValue(reminder.text, forKey: "reminder")
attribute.setValue(value.text, forKey: "value")
try manageContext.save()
}catch let error as NSError{
}
}
var detailItem: Coursework?
var detailItem2: Task?
{
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.courseworkname
}
if let label = self.dueDateLabel {
label.text = detail.duedate
}
if let label = self.value {
label.text = detail.value
}
if let label = self.courseworkname {
label.text = detail.courseworkname
}
if let label = self.modulename {
label.text = detail.modulename
}
if let label = self.level {
label.text = detail.level
}
if let label = self.mark {
label.text = detail.mark
}
if let label = self.reminder{
label.text = detail.reminder
}
if let label = self.notes{
label.text = detail.notes
}
}
Is it a new attribute? You have to uninstall and reinstall the app when you're changing your CoreData models.
Also just saw that you don't have an IBOutlet defined for progressbar, if you link it it should work.

Expression resolves to an unused function

So I have been messing around with saving and calling from NSUserDefaults and I have made progress but I keep on getting this error.
"Expression resolves to an unused function"
The program is supposed to save a string from a textfield so that if you close the program and open it the string will still be their. Unless, you press save again and then the string (Label) will change.
The problem prevents me from running the program so I have not been able to test the new code that I wrote.
Here is the source code feel free to try it. All of this is written in swift.
//
// ViewController.swift
// Help
//
// Created by Lucas on 9/30/15.
// Copyright (c) 2015 Lucas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet var Savedlbl: UILabel!
#IBOutlet var Textfield: UITextField!
#IBOutlet var Label: UILabel!
var current = ""
var Saved = ""
override func viewDidLoad() {
super.viewDidLoad()
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = currentDefault.valueForKey("saved") as? String
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Set(sender: AnyObject) {
setall()
}
func setall()
{
current = Textfield.text!
Label.text = Textfield.text!
Savedlbl.text = Textfield.text!
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = currentDefault.valueForKey("saved") as? String
currentDefault.setValue(Saved, forKey: "saved")
currentDefault.synchronize
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The line:
currentDefault.synchronize
should be:
currentDefault.synchronize()

Optional() in my text view

For one of my static labels on my main story board, it prints out "Optional("United States"). However, I would like it to print out "United States". So my question is, how do I get rid of the "Optional" part? I've already tried doing:
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
I think the exclamation mark is supposed to "unwrap" some value right? However, even if I do p = placemarks!.first, it prints out "Optional("United States").
Below is the rest of my code just in case you would like some context:
//
// ViewController.swift
// Map Demo Rob 2
//
// Created by Jae Hyun Kim on 8/17/15.
// Copyright © 2015 Jae Hyun Kim. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var latitudeLabel: UILabel!
#IBOutlet weak var longitudeLabel: UILabel!
#IBOutlet weak var courseLabel: UILabel!
#IBOutlet weak var speedLabel: UILabel!
#IBOutlet weak var altitudeLabel: UILabel!
#IBOutlet weak var addressLabel: UILabel!
var manager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
// 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.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
let userLocation: CLLocation = locations[0]
self.latitudeLabel.text = "\(userLocation.coordinate.latitude)"
self.longitudeLabel.text = "\(userLocation.coordinate.longitude)"
self.courseLabel.text = "\(userLocation.course)"
self.speedLabel.text = "\(userLocation.speed)"
self.altitudeLabel.text = "\(userLocation.altitude)"
CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: {(placemarks, error) -> Void in
print(userLocation)
if error != nil {
print(error)
return
}
else {
if let p = placemarks?.first{
self.addressLabel.text = "\(p.country)"
}
}
})
}
}
In
if let p = placemarks!.first{
self.addressLabel.text = "\(p.country)"
}
p.country is an Optional<String>. You need to unwrap that aswell in order to output only it's content (if it exists).
if let country = placemarks?.first?.country {
self.addressLabel.text = country
}

Class has no initializers (Xcode 6.3)

Trying to figure out errors after updating to Xcode 6.3. I have a class thats getting the error 'Class has no initializers' could anyone tell me how to fix this?
class TodayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, BWWalkthroughViewControllerDelegate {
var events: [EKEvent] = []
let eventStore = EKEventStore()
var pttCalendar: EKCalendar?
let walkthroughVC : BWWalkthroughViewController?
#IBOutlet weak var tableView: UITableView!
var dateFormatter = NSDateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
requestCalendarAccess()
let firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunch")
if firstLaunch {
println("Not first launch.")
}
else {
showWalkthrough()
println("First launch, setting NSUserDefault.")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
}
self.tableView.rowHeight = 50
dateFormatter.dateFormat = "EE, MMM dd"
let dateForLabel = dateFormatter.stringFromDate(NSDate())
self.title = dateForLabel
}
You forgot the override func init()
You need an initialiser to set the value
let walkthroughVC : BWWalkthroughViewController?
Setting that as a var will remove the error. It will of course default to nil.

How do I fix this crash? Xcode 6 Swift

I am only coding in two features. MailComposer and WebView. But when I run my app and go to the email interface tab it crashes "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)". When I go to the tab that displays the webview, it works fine. The Webview.loadRequest(request) is messing something up with the mail coding. But I don't know where I can put it to make both features work.
If anyone has any clue how to fix this, please let me know. Thanks.
Here is the coding for the View.Controller.Swift file...
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
#IBOutlet weak var Webview: UIWebView!
#IBOutlet weak var Subject: UITextField!
#IBOutlet weak var Body: UITextView!
var URLPath = "http://google.com"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadAddressURL()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func SendEmail(sender: AnyObject) {
var SubjectText = "Inquiry:"
SubjectText += Subject.text
var MessageBody = Body
var toRecipients = ["phillip.lebsack1#gmail.com"]
var mc: MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(SubjectText)
mc.setMessageBody(MessageBody.text, isHTML: false)
mc.setToRecipients(toRecipients)
self.presentViewController(mc, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
switch result.value{
case MFMailComposeResultCancelled.value:
NSLog("Mail Cancelled")
case MFMailComposeResultSaved.value:
NSLog("Mail Saved")
case MFMailComposeResultSent.value:
NSLog("Mail Sent")
case MFMailComposeResultFailed.value:
NSLog("Mail Sent Failure: %#",[error.localizedDescription])
default:
break
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func loadAddressURL(){
let requestURL = NSURL(string:URLPath)
let request = NSURLRequest(URL: requestURL!)
Webview.loadRequest(request)
}
}
Make sure no warning message and bind all #IBOutlet in your ViewController.

Resources