Optional() in my text view - xcode

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
}

Related

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

Swift error : class RecordSoundsViewController has no initializers

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!

why do i get Fatal error: unexpectedly found nil while unwrapping an optional value... here's my code:

Not sure why this isn't working? any help would be greatly appreciated. Thnks.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var locationManager:CLLocationManager!
#IBOutlet weak var mapView: MKMapView!
#IBAction func nowButton(sender: AnyObject) {
}
#IBOutlet weak var mapLabel: UILabel!
#IBAction func bookButton(sender: AnyObject) {
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
mapView.delegate = self
// 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: [AnyObject]!) {
let regionToZoom = MKCoordinateRegionMake(manager.location.coordinate, MKCoordinateSpanMake(0.05, 0.05))
mapView.setRegion(regionToZoom, animated: true)
}
}
Possible error cause lies in because of this line in didUpdateLocations delegate method:
let regionToZoom = MKCoordinateRegionMake(manager.location.coordinate, MKCoordinateSpanMake(0.05, 0.05))
You need to create region like below line (replace this line with above line):
let regionToZoom = MKCoordinateRegion(center: manager.location.coordinate, span: MKCoordinateSpanMake(0.05, 0.05)));

Hitting Return to save Text Input

I have a text field on my xcode project, how can I do to save the user input just by hitting return on the keyboard, instead of using a button to save it?
ViewController with the new code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textFieldInput: UITextField!
#IBOutlet weak var iphoneSaveCharName: UIButton!
#IBOutlet weak var charOne: UIButton!
#IBOutlet weak var charTwo: UIButton!
#IBOutlet weak var charThree: UIButton!
#IBOutlet weak var charFour: UIButton!
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.
}
// #IBAction func iphoneSaveTextInput(sender: UIButton) -> Void{
//
// let textData = textFieldInput.text
// textFieldInput.hidden = true
// iphoneSaveCharName.hidden = true
// }
var savedText: String!
func textFieldShouldReturn(textFieldInput: UITextField) -> Bool {
savedText = textFieldInput.text
println(savedText)
textFieldInput.resignFirstResponder()
return false
}
#IBAction func editText(sender: AnyObject) {
if sender is UILongPressGestureRecognizer &&
sender.state == UIGestureRecognizerState.Began {
textFieldInput.hidden = false
iphoneSaveCharName.hidden = false
let button = sender.view as UIButton
if button.tag == 1{
charOne.setTitle(savedText, forState: .Normal)
} else if button.tag == 2{
charTwo.setTitle(savedText, forState: .Normal)
} else if button.tag == 3{
charThree.setTitle(savedText, forState: .Normal)
} else if button.tag == 4{
charFour.setTitle(savedText, forState: .Normal)
}
}
}
}
The editText function is a long press gesture recognizer that checks what button is being long pressed.
Set the view controller as a text field delegate and add the appropriate delegate method.
class viewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var textField: UITextField!
var savedText: String!
func textFieldShouldReturn(textField: UITextField) -> Bool {
savedText = textField.text
textField.resignFirstResponder()
return false
}
}

EXC_BAD_INSTRUCTION in Swift

I'm brand new at Swift. So I did this tutorial to make a tip calculator and it worked fine. I started a new project to see if I could recreate it, keeping the original code as reference along the way. I created my app exactly the same way, but using different variable names.
I'm getting this error at the lblABVCalculated.text line:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Any ideas why the following code wouldn't work?
Heading
import UIKit
class FirstViewController: UIViewController {
#IBOutlet weak var txtOG: UITextField!
#IBOutlet weak var txtFG: UITextField!
#IBOutlet weak var lblABVCalculated: UILabel!
var OG = ""
var FG = ""
var answer : Float = 0
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.
}
#IBAction func btnCalculate(sender: UIButton) {
calculateABV()
}
#IBAction func btnClear(sender: UIButton) {
txtOG.text = ""
txtFG.text = ""
lblABVCalculated.text = "ABV"
}
func calculateABV() -> Bool {
OG = txtOG.text
FG = txtFG.text
var fOG = (OG as NSString).floatValue
var fFG = (FG as NSString).floatValue
answer = fOG * (fFG * 0.01)
var answerFormat : NSString = NSString(format: "%0.2f", answer)
lblABVCalculated.text = "ABV: \(answerFormat)"
// Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
return true
}
}

Resources