Error after upgrading Xcode Expected declaration - xcode

#IBAction func newPhoto(sender: AnyObject) {
if isCameraAvailable() && doesCameraSupportTakingPhotos(){
imagePicker.sourceType = .Camera
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = true
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
}
else {
print("Camera is not available")
}
The error occurs in place of else { -expected Declaration
- Help me please!

Move One } before else to the end of If else statement
#IBAction func newPhoto(sender: AnyObject) {
if isCameraAvailable() && doesCameraSupportTakingPhotos(){
imagePicker.sourceType = .Camera
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = true
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}
else {
print("Camera is not available")
}
}

Related

NSAlert - how can I present a view as a sheet and get a return value in Swift3?

I have the following code working ok:
func alertDialog(question: String, text: String) -> Bool {
let alert: NSAlert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.warning
alert.addButton(withTitle: "Yes Please")
alert.addButton(withTitle: "No Thank You")
changedItem = false
return alert.runModal() == NSAlertFirstButtonReturn
I check the value of NSAlertFirstButtonReturn like this:
func tableViewSelectionDidChange(_ notification: Notification)
{
print (#function, "changedItem", changedItem!)
if changedItem == true {
let answer = alertDialog(question: "Save your changes?", text: "Unsaved changes will be shredded.")
print(#function, "answer: ", answer)
if answer == true {
print(#function, "TRUE")
saveChanges(self)
changedItem = false
}
}
I'm struggling to perform the same function, but show the alert as a sheet.
I cannot figure how to present and test the result. I'm currently getting all true or all false.
I've tried various permutations such as follows with no joy, and would appreciate any help.
//instead of the return sheetModal
var result: Int! = 0
//result = false
alert.beginSheetModal(for: self.view.window!, completionHandler: { (NSAlertFirstButtonReturn) -> Void in
if NSAlertFirstButtonReturn.hashValue == 1000 {
result = 1
} else {
result = 0
}
})
print(#function, "NSAlertFirstButtonReturn: ", NSAlertFirstButtonReturn.hashValue)
changedItem = false
if result == 1 {
return true
} else {
return false
}
Unlike the runModal method beginSheetModal(for:completionHandler:) works asynchronously. It is impossible to return a value from a function / method including an asynchronous task.
Add a completion handler to the alertDialog method:
func alertDialog(question: String, text: String, completion: #escaping (Bool)->() ) {
let alert: NSAlert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.warning
alert.addButton(withTitle: "Yes Please")
alert.addButton(withTitle: "No Thank You")
changedItem = false
alert.beginSheetModal(for: self.view.window!, completionHandler: { result in
completion(result == NSAlertFirstButtonReturn)
})
}
And use the method:
func tableViewSelectionDidChange(_ notification: Notification)
{
print (#function, "changedItem", changedItem!)
if changedItem == true {
alertDialog(question: "Save your changes?", text: "Unsaved changes will be shredded.", completion: { [unowned self] answer in
print(#function, "answer: ", answer)
if answer == true {
print(#function, "TRUE")
self.saveChanges(self)
self.changedItem = false
}
})
}
}
The functionality is practically the same but the execution is asynchronous.
Side-note: Why is changedItem optional? It seems to be a real Bool with just two states.

AVAudioPath not working - Swift

I am trying to play a song based on the instrument the user selects. Here is my code:
#IBAction func play(sender: AnyObject) {
if isPlaying == false {
player.play()
isPlaying = true
}
}
#IBAction func stop(sender: AnyObject) {
if isPlaying == true {
player.stop()
isPlaying = false
}
}
#IBAction func pause(sender: AnyObject) {
if isPlaying == true {
isPlaying = false
player.pause()
}
}
var player = AVAudioPlayer()
var audioPath = NSBundle.mainBundle().pathForResource("Iditarod Bass", ofType: "m4a")
var isPlaying = Bool()
#IBOutlet var instrumentSelect: UISegmentedControl!
#IBAction func didChangeInstrument(sender: AnyObject) {
if isPlaying == false {
if instrumentSelect.selectedSegmentIndex == 0 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Bass", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
} else if instrumentSelect.selectedSegmentIndex == 1 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Cello", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
} else if instrumentSelect.selectedSegmentIndex == 2 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Viola", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
} else if instrumentSelect.selectedSegmentIndex == 3 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Violin 1", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
} else if instrumentSelect.selectedSegmentIndex == 4 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Violin 2", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
}
}
}
All of them work fine except for the instrumentSelect.selectedSegmentIndex == 1. I don't know why. I get an EXC_BAD_INSTRUCTION that says fatal error: unexpectedly found nil while unwrapping an Optional value. The file is working fine, and I have cleaned the project numerous times. I have typed everything correctly. Why is that one not working? I am very confused about this, and I appreciate your help.
The file was not being added to the app target. It was added to the project only. Thanks #matt for helping me.

In change of Swift 2 Extra argument ' error' in call

Upgrade to Xcode 7 Swift 2 and SDK for iOS 9. I get the error "extra argument" error "in call" my code is:
let myUrl = NSURL(string: "http://localhost/SwiftAppAndMySQL/scripts/registerUser.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "userEmail=\(userEmail)&userFirstName=\(userFirstName)&userLastName=\(userLastName)&userPassword=\(userPassword)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
dispatch_async(dispatch_get_main_queue())
{
spinningActivity.hide(true)
if error != nil {
self.displayAlertMessage(error.localizedDescription)
return
}
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
if let parseJSON = json {
var userId = parseJSON["userId"] as? String
if( userId != nil)
{
var myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
} else {
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
self.displayAlertMessage(errorMessage!)
}
}
}
}
}).resume()
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler ) asks you for 3 optionals arguments and you're giving 3 forceds unwrapping arguments.
try change
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data:NSData!, response:NSURLResponse!, error:NSError!)
to
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?)
Now is working, I replaced the previous code with this::
let myUrl = NSURL(string: "http://dcapp1.testingview.com/DryCleanAppClientes/scripts/registerUser.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let postString = "userEmail=\(userEmail)&userFirstName=\(userFirstName)&userLastName=\(userLastName)&userPassword=\(userPassword)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
print(postString)
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
dispatch_async(dispatch_get_main_queue())
{
spinningActivity.hide(true)
if error != nil {
self.displayAlertMessage(error!.localizedDescription)
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
if let parseJSON = json {
let userId = parseJSON["userId"] as? String
if( userId != nil)
{
let myAlert = UIAlertController(title: "Mensaje", message: "¡Registro exitoso!", preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){(action) in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
} else {
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
self.displayAlertMessage(errorMessage!)
}
}
}
} catch _ as NSError {
}
}
}).resume()
}

Display alert keeps logging me out after error message on xcode using swift

I'm creating an Instagram like app, and whenever I dismiss the display alert that is displayed when an image or text is missing, it logs me out and logs me back in. How can I make it so that when I click "ok", only the display alert goes away and doesn't log me out?
Here is my image posting view control code:
import UIKit
import Parse
import Foundation
class PostViewControllerPage1: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
func displayAlert(title:String, error:String) {
var alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
var photoSelected:Bool = false
#IBOutlet weak var imageToPost: UIImageView!
#IBAction func chooseImage(sender: AnyObject) {
var image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
println("Image selected")
self.dismissViewControllerAnimated(true, completion: nil)
imageToPost.image = image
photoSelected = true
}
#IBOutlet weak var imageDescription: UITextField!
#IBAction func postImage(sender: AnyObject) {
var error = ""
if (photoSelected == false) {
error = "Please select an image to post"
} else if (imageDescription.text == "") {
error = "Please enter a message"
}
if (error != "") {
displayAlert("Cannot Post Image", error: error)
}
else {
var post = PFObject(className: "Post")
post["Title"] = imageDescription.text
post.saveInBackgroundWithBlock{(success: Bool, error: NSError?) -> Void in
if success == false {
self.displayAlert("Could Not Post Image", error: "Please try again later")
} else {
let imageData = UIImagePNGRepresentation(self.imageToPost.image)
let imageFile = PFFile(name: "image.png", data: imageData)
post["imageFile"] = imageFile
post.saveInBackgroundWithBlock{(success: Bool, error: NSError?) -> Void in
if success == false {
self.displayAlert("Could Not Post Image", error: "Please try again later")
} else {
println("posted successfully")
}
}
}
}
}
}
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.
}
}
What am I doing wrong?
Here is my login code, because I feel like that might be a part of the issue:
import Foundation
import Parse
import UIKit
import Bolts
class LoginViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var loginStatusLabel: UILabel!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
emailTextField.delegate = self
passwordTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func loginButtonPress(sender: AnyObject) {
login(emailTextField.text, password: passwordTextField.text)
}
func login(email: String, password: String)
{
PFUser.logInWithUsernameInBackground(email, password: password)
{
(user: PFUser?, error: NSError?) -> Void in
if user != nil
{
user!.fetchInBackground()
if user!.objectForKey("emailVerified") as! Bool
{
self.loginStatusLabel.text = "Success!"
println("successfulLogin")
self.performSegueWithIdentifier("login", sender: self)
}
else if !(user!.objectForKey("emailVerified") as! Bool)
{
self.loginStatusLabel.text = "Verify your email address!"
}
else // status is "missing"
{
//TODO: Handle this error better
self.loginStatusLabel.text = "Verification status: Missing"
}
}
else
{
if let errorField = error!.userInfo
{
self.loginStatusLabel.text = (errorField["error"] as! NSString) as String
}
else
{
// No userInfo dictionary present
// Help from http://stackoverflow.com/questions/25381338/nsobject-anyobject-does-not-have-a-member-named-subscript-error-in-xcode
}
}
}
}
override func viewDidAppear(animated: Bool) {
if PFUser.currentUser() != nil {
self.performSegueWithIdentifier("login", sender: self)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBarHidden = true
}
override func viewWillDisappear(animated: Bool) {
self.navigationController?.navigationBarHidden = false
}
}
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.dismissViewControllerAnimated in this line will dismiss view controller that show alert and not an alert itself. So all you have to do is comment or delete this line of code

Saving an image to special album swift

I want to add a new photo to certain album, I'm trying to do it like that:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
albumName = "\(data.objectAtIndex(indexPath.row))"
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Choose image source", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Take Photo", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
imagePickerController.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(imagePickerController, animated: true, completion: {})
}))
actionSheet.addAction(UIAlertAction(title: "Camera Roll", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let image:UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
var groupToAddTo: ALAssetsGroup = ALAssetsGroup()
self.library.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupAlbum),
usingBlock: {
(group: ALAssetsGroup!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if group.valueForProperty(ALAssetsGroupPropertyName).isEqualToString(self.albumName){
groupToAddTo = group
}
},
failureBlock: {
(myerror: NSError!) -> Void in
println("error occurred: \(myerror.localizedDescription)")
})
var img: CGImageRef = image.CGImage
self.library.writeImageToSavedPhotosAlbum(img, metadata: nil, completionBlock: {
(assetUrl: NSURL!, error: NSError!) -> Void in
if error.code == 0 {
println("saved image completed: \(assetUrl)")
self.library.assetForURL(assetUrl, resultBlock: { (asset: ALAsset!) -> Void in
groupToAddTo.addAsset(asset)
return
}, failureBlock: {
(myerror: NSError!) -> Void in
println("error occurred: \(myerror.localizedDescription)")
})
} else {
println("saved image failed. \(error.localizedDescription) code \(error.code)")
}
} )
}
However, when I run this code, I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
in this line:
if group.valueForProperty(ALAssetsGroupPropertyName).isEqualToString(self.albumName){
So, the question is that, how to save an image to certain album in swift?
I am betting albumName is an optional value.
You should put an if statement to judge if almbumName is nil. When it's nil, create a newalbum name on your iPhone.
First:
if group != nil {
if group.valueForProperty(ALAssetsGroupPropertyName).isEqualToString(self.albumNames[indexPath.row]){
groupToAddTo = group
}
}
Second, when error = nil your app will crash because of "if error.code == 0." Do "if error == nil" instead.

Resources