Crash after cancel on message form - swift

I want to send an message through my app - everything works like it should, except, if the user aborts the Screen with the "Cancel" in the upper right corner, the App will get black and crashes.
I think it has something to do with the Views, so that the App View won't come back, but I don't know how and why. I've made breakpoints, but the app crashes before these.
Here is the whole code of this:
import UIKit
import MessageUI
class LoanTableCell: UITableViewCell, UIAlertViewDelegate, UINavigationControllerDelegate, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var imageData: Data?
var userEmail: String?
var userNumber: String?
var popUp: UIView?
// Label Outlets
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var amountLabel: UILabel!
#IBOutlet weak var currencyLabel: UILabel!
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var noteLabel: UILabel!
#IBOutlet weak var dueLabel: UILabel!
#IBOutlet weak var moreInfos: UIView!
#IBOutlet weak var showImageButton: UIButton!
#IBOutlet weak var remindButton: UIButton!
#IBAction func remindUser(_ sender: Any) {
let alert: UIAlertController = UIAlertController(title: "remind by:", message: nil, preferredStyle: .actionSheet)
let view = storyboard.instantiateViewController(withIdentifier: "LoanView") as! LoanViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let remindByEmail = UIAlertAction(title: "E-Mail", style: UIAlertActionStyle.default) {
UIAlertAction in
self.sendEmail()
} // Email senden....
let remindByNumber = UIAlertAction(title: "Phone Message", style: UIAlertActionStyle.default) {
UIAlertAction in
self.sendSMS()
} // SMS senden...
let cancelRemind = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
print("cancel")
} // Abbrechen
//Aktionen ausführen
if(userNumber != ""){
alert.addAction(remindByNumber)
}
if(userEmail != ""){
alert.addAction(remindByEmail)
}
alert.addAction(cancelRemind)
//Controller anzeigen
appDelegate.window?.rootViewController = view
view.present(alert, animated: true, completion: nil)
}
#IBAction func showImage(_ sender: Any) {
if (imageData?.isEmpty == false) {
popUp = UIView(frame: CGRect(x: 0, y: 20, width: (window?.frame.width)!, height: (window?.frame.height)!))
popUp?.backgroundColor = UIColor.black
window?.addSubview(popUp!)
popUp?.isHidden = false
let imageView = UIImageView(frame: CGRect(x: 15, y: 15, width: ((window?.frame.maxX)! - 30), height: ((window?.frame.maxY)! - 50)))
imageView.image = UIImage(data: imageData!)
imageView.contentMode = .scaleAspectFit
popUp?.addSubview(imageView)
let closeButton = UIButton(frame: CGRect(x: ((window?.frame.maxX)! - 40), y: 5, width: 35, height: 35))
closeButton.setImage( imageLiteral(resourceName: "closeImage"), for: .normal)
closeButton.addTarget(self, action: #selector(closeImageView), for: .touchUpInside)
popUp?.addSubview(closeButton)
}
}
#objc func closeImageView() {
popUp?.isHidden = true
}
func sendEmail() {
let view = storyboard.instantiateViewController(withIdentifier: "LoanView") as! LoanViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if MFMailComposeViewController.canSendMail() {
let reminderMessage: String = „Some Text„
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([userEmail!])
mail.setSubject("Urgent Loan-Reminder")
mail.setMessageBody(reminderMessage, isHTML: true)
appDelegate.window?.rootViewController = view
view.present(mail, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "No E-Mail Account found...", message: "to send E-Mails, you have to configure at least one E-Mail account on your Device.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
appDelegate.window?.rootViewController = view
view.present(alert, animated: true, completion: nil)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
print("mail sent")
}
func sendSMS() {
let view = storyboard.instantiateViewController(withIdentifier: "LoanView") as! LoanViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if MFMessageComposeViewController.canSendText() {
let reminderMessage: String = „Some Text„
let message = MFMessageComposeViewController()
message.messageComposeDelegate = self
message.recipients = [userNumber!]
message.body = reminderMessage
appDelegate.window?.rootViewController = view
view.present(message, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "No Message Account...", message: "to send Messages, you need a Phone account.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
appDelegate.window?.rootViewController = view
view.present(alert, animated: true, completion: nil)
}
}
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
controller.dismiss(animated: true, completion: nil)
print("message sent")
}
}
If I hit the cancel button in the upper right, I will get this error in the AppDelegate file:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x5a1b7831c08)
Seems like I've forgotten something.

A UITableViewCell should not be responsible for such actions, the cell should send a notification or it should be connected with a delegate method. Then the UIViewController should perform these actions.
protocol RemindUserDelegate: class {
func buttonPressed()
}
class LoanTableCell: UITableViewCell {
weak var delegate: RemindUserDelegate?
}
class ViewController: UIViewController, RemindUserDelegate,MFMailComposeViewControllerDelegate, MFMessageComposeVie wControllerDelegate {
func buttonPressed() {
}
}
and at cellForRow add:
cell.delegate = self
and on the cell perform : self.delegate?.buttonPressed()
then the UIViewController can take it from there. You can also pass info with userData.

Related

How to make actionsheet pop over a bar button on iPhone

I know how to make an action sheet pop over a button on iPad but not for iPhone. it seems that on iphone the action sheet doesn't have popoverPresentationController:
#IBAction func addChannel(_ sender: Any) {
let sender = sender as? UIBarButtonItem
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let addChanel = UIAlertAction(title: "Add a Channel", style: .default) { (_) in
self.addChannel()
}
let addContact = UIAlertAction(title: "Add a Contact", style: .default){ _ in
self.addContact()
}
actionSheet.addAction(addChanel)
actionSheet.addAction(addContact)
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel))
// actionSheet.popoverPresentationControlle
if let popover = actionSheet.popoverPresentationController{
actionSheet.popoverPresentationController?.barButtonItem = sender
actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.down
}
self.present(actionSheet, animated: true)
}
I want the action sheet pop over a button just like what WeChat + button does. Other stackoverflow answers are too old and not workable
Any idea is welcome!
Source.
You cannot use UIAlertController as a popover on iPhones. One of alternatives is using a UITableView or something inside new UIViewController, which you can create like described below (Swift 5.0).
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
#IBOutlet private weak var button: UIButton!
#IBAction func buttonAction() {
let vc = UIViewController()
vc.view.backgroundColor = UIColor.blue
vc.preferredContentSize = CGSize(width: 200, height: 200)
vc.modalPresentationStyle = .popover
let ppc = vc.popoverPresentationController
ppc?.permittedArrowDirections = .any
ppc?.delegate = self
ppc?.sourceView = button
present(vc, animated: true, completion: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
Also, popoverPresentationController has property called barButtonItem which you can assign to your nav bar button.

Custom Tableview Cell Disappears when reloading table with a new picture

I have a very strange issue occurring that I have not seen before while developing. It makes it very difficult to troubleshoot due to the fact the app is not crashing and there is no erroneous debug output in the console window.
I have an edit user profile ViewController. On this page it displays the users first and last name, e-mail and phone number, along with a picture. This is all being pulled from Firebase and is working fine. The "picture" you see is an actual JPG that is "uploaded" when someone creates an account, this way the photo URL is stored in their database and I can retrieve it to display a photo. In theory, when "editing" a profile, the user would see a real pic in there, and "change" it with the one they are taking or upload.
The issue I am having is that when I finish selecting a picture from the gallery or take one from the camera, it correctly dismisses the camera or gallery, but the "tableviewcell" dissapears, and I do not see the picture or the text. Oddly enough, the text fields remain that are not part of the table. The intent is to have the pic that is "taken" temporarily appear in the UIImage view (which lives in the tableviewcell) and then when the user hits "save", it will upload to FireBase (that part I know how to do). That VC then gets dismissed and the data on in ProfileVC is reloaded from FireBase with the new pic.
I have the firebase part down as well as I correctly (I think) coded the image picker, but there has to be something I am missing as to why the temporary image is not displaying.
As an additional troubleshooting step I commented out the line: self.editProfileTable.reloadData() under the function imagePickerContoller in the EditProfileVC.swift file. When I did that, after hitting "chose Photo" that view dismisses and it goes right back to the Before Update Picture picture below. It has to be something with the table, but I am just not seeing it.
I have included all relevant code below.
EditProfileVC.swift
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
class EditProfileVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, Alertable, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var delegate : ImagePickerDelegate?
var tempImage : UIImage?
var imagePicker : UIImagePickerController?
#IBOutlet var editProfileTable: UITableView!
#IBOutlet var editEmailTextField: UITextField!
#IBOutlet var editMobileTextField: UITextField!
var editProfileInfo = [EditProfileModel]()
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return editProfileInfo.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "editprofilecell", for: indexPath) as! EditProfileTableViewCell
let editprofile: EditProfileModel
editprofile = editProfileInfo[indexPath.row]
cell.firstNameLabel.text = editprofile.firstname
cell.lastNameLabel.text = editprofile.lastname
cell.emailLabel.text = editprofile.email
cell.mobileLabel.text = editprofile.mobile
cell.tapButton = {(user) in
self.pickImage()
}
if tempImage == nil {
DataService.instance.REF_USERS.observeSingleEvent(of: .value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
self.editProfileInfo.removeAll()
for snap in snapshot {
if snap.key == Auth.auth().currentUser?.uid {
let imageUrl = snap.childSnapshot(forPath: "userPhoto").value
// print(imageUrl)
let storage = Storage.storage()
let ref = storage.reference(forURL: imageUrl as! String)
ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
if error != nil {
// Uh-oh, an error occurred!
} else {
cell.updateProfileImage.image = UIImage(data: data!)
}
}
}
}
}
})
}
delegate?.pickImage()
cell.updateProfileImage.image = tempImage
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
editEmailTextField.delegate = self
editMobileTextField.delegate = self
view.bindtoKeyboard()
imagePicker = UIImagePickerController()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleScreenTap(sender:)))
self.view.addGestureRecognizer(tap)
DataService.instance.REF_USERS.observeSingleEvent(of: .value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
self.editProfileInfo.removeAll()
for snap in snapshot {
if snap.key == Auth.auth().currentUser?.uid {
let profileObject = snap.value as? [String: AnyObject]
let profileFirstName = profileObject?["first_name"]
let profileLastName = profileObject?["last_name"]
let profileMobile = profileObject?["mobile_number"]
let profileEmail = Auth.auth().currentUser?.email
let editprofile = EditProfileModel(firstname: profileFirstName as! String?, lastname: profileLastName as! String?, email: profileEmail , mobile: profileMobile as! String?)
self.editProfileInfo.append(editprofile)
}
self.editProfileTable.reloadData()
}
}
})
delegate?.pickImage()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
#objc func handleScreenTap(sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
func pickImage() {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallery()
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
// let imagePicker = UIImagePickerController()
// imagePicker.delegate = self
// imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
// imagePicker.allowsEditing = false
// self.present(imagePicker, animated: true, completion: nil)
}
func openCamera()
{
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerController.SourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func openGallery()
{
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have perission to access gallery.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
tempImage = pickedImage
self.editProfileTable.reloadData()
dismiss(animated: true, completion: nil)
// imageViewPic.image = pickedImage
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
EditProfileModel.swift
class EditProfileModel {
var firstname: String?
var lastname: String?
var email: String?
var mobile: String?
init(firstname: String?, lastname: String?, email: String?, mobile: String?){
self.firstname = firstname
self.lastname = lastname
self.email = email
self.mobile = mobile
}
}
EditProfileTableViewCell.swift
import UIKit
import Foundation
var delegate : ImagePickerDelegate?
class EditProfileTableViewCell: UITableViewCell {
#IBOutlet var updateProfileImage: UIImageView!
#IBOutlet var firstNameLabel: UILabel!
#IBOutlet var lastNameLabel: UILabel!
#IBOutlet var emailLabel: UILabel!
#IBOutlet var mobileLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func btdDetailsClick(_ sender: Any) {
tapButton?(self)
delegate?.pickImage()
}
var tapButton: ((UITableViewCell) -> Void)?
}
ImagePicker.swift
import UIKit
import Foundation
protocol ImagePickerDelegate {
func pickImage()
}
Before Update Picture button is pressed
After Update Image button pressed and all code above is run

Swift Unexpectedly found nil while unwrapping an Optional value while pass image to another ViewController

I have two VCs. The first one contains an imagePicker from gallery and a callback function that sends and image to the chatLog... I want to send the selected photo to the 2nd VC
if let selectedImage = selectedImageFromPicker {
//self.callback?(selectedImage)
detailImageViewController.aImage = selectedImage
}
I created the 2nd VC as controller for PreviewImage with buttons cancel or accept. I tried to pass the image displayed on the 2nd VC back to 1st VC this way but it shows me:
Fatal error: Unexpectedly found nil while unwrapping an Optional value.
How can I fix that?
var t : EVTPhotoTekingHelper!
#objc func actionSend() {
if aImage != nil{
t.callback?(aImage!)
}
else {
print("nil")
}
dismiss(animated: true, completion: nil)
}
UPDATED:
My 1st VC
typealias PhotoTekingHelperCallBack = (UIImage?) -> ()
class EVTPhotoTekingHelper: NSObject {
// View controller on which AlertViewController and UIImageViewController are present
weak var viewController: UIViewController!
var imagePickerController: UIImagePickerController?
var callback: PhotoTekingHelperCallBack?
var photoTakinHelper: EVTPhotoTekingHelper!
// MARK: - Initialization
init(viewController: UIViewController, callback: #escaping PhotoTekingHelperCallBack) {
self.viewController = viewController
self.callback = callback
super.init()
showPhotoSourceSelection()
}
func showPhotoSourceSelection() {
let alertController = UIAlertController.init(title: nil,
message: "Message?",
preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let photoLibraryAction = UIAlertAction(title: "from library", style: .default) { (action) in
self.showImagePickerController(sourceType: .photoLibrary)
}
alertController.addAction(cancelAction)
alertController.addAction(photoLibraryAction)
if UIImagePickerController.isFlashAvailable(for: .rear) {
let cameraAction = UIAlertAction.init(title: "from camera", style: .default, handler: { (action) in
self.showImagePickerController(sourceType: .camera)
})
alertController.addAction(cameraAction)
}
viewController.present(alertController, animated: true, completion: nil)
}
func showImagePickerController(sourceType: UIImagePickerControllerSourceType) {
imagePickerController = UIImagePickerController.init()
imagePickerController!.sourceType = sourceType
imagePickerController!.delegate = self
viewController.present(imagePickerController!, animated: true, completion: nil)
}
}
Extension from 1st VC
extension EVTPhotoTekingHelper: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker: UIImage?
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImageFromPicker = editedImage
} else if let originImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
selectedImageFromPicker = originImage
}
let detailImageViewController = EVImagePreviewController()
let ncDetailImageViewController = UINavigationController(rootViewController: detailImageViewController)
if let selectedImage = selectedImageFromPicker {
//self.callback?(selectedImage)
detailImageViewController.aImage = selectedImage
}
viewController.dismiss(animated: false, completion: nil)
viewController.parent?.present(ncDetailImageViewController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
viewController.dismiss(animated: false, completion: nil)
}
}
My 2nd VC
class EVImagePreviewController: UIViewController, UIScrollViewDelegate {
var t : EVTPhotoTekingHelper!
var aImageView: UIImageView!
var aImage: UIImage!
private var aScrollView: UIScrollView!
override func viewDidAppear(_ animated: Bool) {
aImageView = UIImageView(frame: CGRect(x: 0, y: 75, width: (aImage?.size.width)!, height: (aImage?.size.height)!))
aImageView.contentMode = .scaleAspectFit
aImageView.image = aImage
aScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
aScrollView.backgroundColor = .clear
aScrollView.contentSize = CGSize(width: view.frame.size.width, height: view.frame.height)
aScrollView.minimumZoomScale = 0.2
aScrollView.maximumZoomScale = 2.3
aScrollView.clipsToBounds = true
aScrollView.delegate = self
aScrollView.addSubview(aImageView)
view.addSubview(aScrollView)
aImageView.center = CGPoint(x: aScrollView.bounds.midX, y: aScrollView.bounds.midY - 35)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(actionSend))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(actionBack))
}
// MARK: - IBAction
#objc func actionBack() {
dismiss(animated: false, completion: nil)
}
#objc func actionSend() {
print("\(t)")
if aImage != nil{
t.callback?(aImage!)
}
else {
print("nil")
}
//self.callback?(aImage)
dismiss(animated: true, completion: nil)
}
// MARK: - UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return aImageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let subView = scrollView.subviews[0]
let offsetX = max((scrollView.bounds.width - scrollView.contentSize.width) * 0.5, 0.0)
let offsetY = max((scrollView.bounds.height - scrollView.contentSize.height) * 0.5, 0.0)
subView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
}
}
Here you dismiss your first view controller before you present your 2nd one from the parent of your first view controller:
viewController.dismiss(animated: false, completion: nil)
To me so far doesn't make sense. Its not clear where is the callback implementation is.
My guess that the nil exception is not for the UIImage for sure. its somewhere
inside your callback implementation.

how do I show man all users saved in core data

can anyone help me please
how do I show all users
import CoreData
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var Username: UITextField!
#IBOutlet weak var Password: UITextField!
var array = NSMutableArray()
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 Login(_ sender: Any)
{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
//let predicate = NSPredicate(format: "name == %# && password == %#", Username.text! ,Password.text! )
//request.predicate = predicate
request.fetchLimit = 1
do
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let users = try! context.fetch(request)
// for var i in 0 ..< Users.count
if(users.count > 0)
{
let user = users.first as? Users
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "UsersData") as? UsersData
nextViewController?.userInfo = user
self.present(nextViewController!, animated:true, completion:nil)
}
else
{
let alertController = UIAlertController(title: "",message:"No user Found", preferredStyle: .alert)
let OKAction = UIAlertAction(title:"Ok", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
#IBAction func RegisterButton(_ sender: Any) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "RegisterPage") as? RegisterPage
self.present(nextViewController!, animated:true, completion:nil)
}
}
this is where I save values
this is where I get I data from
class RegisterPage: UIViewController {
#IBOutlet weak var UsernameRegister: UITextField!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var Mobile: UITextField!
#IBOutlet weak var PasswordRegister: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Register(_ sender: Any) {
if (UsernameRegister.text == "" || email.text == "" || Mobile.text == "" || PasswordRegister.text == "" )
{
let alertController = UIAlertController(title: "Note",message:"All fields are required", preferredStyle: .alert)
let OKAction = UIAlertAction(title:"Ok", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
else if !validateEmail(candidate:email.text!)
{
let alertController = UIAlertController(title: "",message:"Email not valid", preferredStyle: .alert)
let OKAction = UIAlertAction(title:"Ok", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
else if(UsernameRegister.text != "" && email.text != "" && Mobile.text != "" && PasswordRegister.text != "" )
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let userData = NSEntityDescription.insertNewObject(forEntityName:"Users",into:context)
userData.setValue(UsernameRegister.text, forKey: "name")
userData.setValue(email.text, forKey: "email")
userData.setValue(Mobile.text, forKey: "mobile")
userData.setValue(PasswordRegister.text, forKey: "password")
print(userData)
do
{
try context.save()
print(userData)
}
catch
{
print("error")
}
}
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController =
storyBoard.instantiateViewController(withIdentifier: "ViewController") as? ViewController
self.present(nextViewController!, animated:true, completion:nil)

How do I dismiss the blureffect after the user pressed a alternativ in alertview?

This is the blureffect and the alert that showes up if the user wants to go back. i could not find anything that I understod so I hope that someone here could help me. Thanks in advice for your help!
This is all the code please but the new code in.
//
// Visartotal.swift
// Segment controll
//
// Created by Simon Harrysson on 2017-01-28.
// Copyright © 2017 Simon Harrysson. All rights reserved.
//
import UIKit
var Allabetygtillsamans: Double = 0
class Visartotal: UIViewController
{
#IBOutlet weak var Tillbaka: UIButton!
#IBOutlet weak var Börjaomknapp: UIButton!
#IBOutlet weak var Visartotalreligion: UILabel!
#IBOutlet weak var VisartotalIMusik: UILabel!
#IBOutlet weak var Visartotaltmerit: UILabel!
#IBOutlet weak var VisartotalBild: UILabel!
#IBOutlet weak var Visartotalmatematik:UILabel!
#IBOutlet weak var VisartotalEngelska: UILabel!
var blurEffectView: UIVisualEffectView?
override func viewDidAppear(_ animated: Bool)
{
self.blurEffect = UIBlurEffect(style: .dark)
self.blurEffectView = UIVisualEffectView(effect: self.blurEffect)
blurEffectView?.frame = view.bounds
blurEffectView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
}
var blurEffect: UIBlurEffect?
#IBAction func TillbakaAction(_ sender: UIButton)
{
createAlert(title: "Är du säker på att du vill börja om?", message: "Ifyllda betyg nollställs")
blurEffectView = UIVisualEffectView(effect: blurEffect)
view.addSubview(blurEffectView!)
}
func createAlert (title:String, message:String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
//CREATING ON BUTTON
alert.addAction(UIAlertAction(title: "Ja", style: UIAlertActionStyle.default, handler: {
(action) in
alert.dismiss(animated: true, completion: nil)
print ("Jag vill gå tillbaka")
self.performSegue(withIdentifier: "Tillbaka", sender: nil)
self.blurEffectView?.removeFromSuperview()
}))
alert.addAction(UIAlertAction(title: "Nej", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
print("Nej, jag vill inte gå tillbaka")
self.blurEffectView?.removeFromSuperview()
}))
self.present(alert, animated: true, completion: nil)
}
override func viewDidLoad()
{
let Allabetygtillsamans = MusikbetygIDouble + BildbetygValtDouble + MatematikbetygvaltIDouble + ReligionbetygvaltDouble + EngelskabetygvaltDouble
Visartotaltmerit.font = UIFont(name: "Arial", size: 21)
let totalameritet = String(Allabetygtillsamans)
VisartotalIMusik.text = MusikbetygValt
VisartotalBild.text = BildbetygValt
Visartotalmatematik.text = Matematikbetygvalt
Visartotalreligion.text = Religionbetygvalt
VisartotalEngelska.text = Engelskabetygvalt
Visartotaltmerit.text = totalameritet + ("p")
if BildbetygValt == "F"
{
VisartotalBild.textColor = UIColor.red
}
if MusikbetygValt == "F"
{
VisartotalIMusik.textColor = UIColor.red
}
if Matematikbetygvalt == "F"
{
Visartotalmatematik.textColor = UIColor.red
}
if Religionbetygvalt == "F"
{
Visartotalreligion.textColor = UIColor.red
}
if Engelskabetygvalt == "F"
{
VisartotalEngelska.textColor = UIColor.red
}
switch Allabetygtillsamans {
case 290...340:
Visartotaltmerit.textColor = UIColor.green
Visartotaltmerit.backgroundColor = UIColor.clear
Visartotaltmerit.backgroundColor = UIColor.clear
case 230...290:
Visartotaltmerit.textColor = UIColor.yellow
Visartotaltmerit.backgroundColor = UIColor.clear
Visartotaltmerit.backgroundColor = UIColor.clear
case 220...230:
Visartotaltmerit.textColor = UIColor.orange
Visartotaltmerit.backgroundColor = UIColor.clear
case 0...220:
Visartotaltmerit.textColor = UIColor.red
Visartotaltmerit.backgroundColor = UIColor.clear
default:
print("defult")
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}
You will need to create a blurEffectView variable that you can access from outside the scope of your tillbakaAction function - somewhere in the viewController. Then, in your UIAlertActions you can say self.blurEffectView.removeFromSuperview() to remove it. There will be no animation - it'll just disappear.
Also, as another commenter noted, you don't need to say alert.dismiss... as that happens automatically.
As an example for your variable, this would work:
var blurEffectView: UIVisualEffectView?
#IBAction func tillbakaAction(_ sender: UIButton) {
...
self.blurEffectView = UIVisualEffectView(effect: blurEffect)
...
}
And in your action:
alert.addAction(UIAlertAction(title: "Ja", style: UIAlertActionStyle.default, handler: {
(action) in
self.blurEffectView?.removeFromSuperview()
...