Why is my data is not writing to Firebase - App crashes due to setObjectForKey: key cannot be nil - ios

for the past two weeks i've been having a struggle to write data to firebase, although the tutorials seem so simple :/....My app has a view controller and a tableview controller. users can add an event Title, event date and description (strings) and add a picture as well. Whenever i try to run the simulator it crashes on me! See code below. Please please help me out this is really getting frustrating.. Even if I place breakpoints in the code on top it crashes.. If someone can help me in a chat that would be awesome or maybe send the file to cause its been too long seriously I need an answer so i understand the problem.
import UIKit
import Firebase
import FirebaseDatabaseUI
class EventViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//outlets for text & image
#IBOutlet weak var photoImageView: UIImageView!
#IBOutlet weak var eventName: UITextField!
#IBOutlet weak var eventDate: UITextField!
#IBOutlet weak var eventDes: UITextView!
//Database connection
let rootref = FIRDatabase().reference()
var imagePicker: UIImagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func submitEvent(sender: AnyObject) {
let name = eventName.text
let date = eventDate.text
let text = eventDes.text
var data: NSData = NSData()
var user = NSDictionary()//declare here
if let image = photoImageView.image {
data = UIImageJPEGRepresentation(image,0.1)!
}
let base64String = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
if let unwrappedName = name , unwrappedDate = date, unwrappedText = text{
//use your declared dictionary
user = ["name":unwrappedName, "date":unwrappedDate, "text":unwrappedText, "photoBase64":base64String]
}
//Add firebase child node
//let event = FIRDatabase().reference().child(name!)
//Do not create one more reference to database
rootref.child(name!)
rootref.child(name!).setValue(user)
navigationController?.popViewControllerAnimated(true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
//UIImagePickerControllerDelegate methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
photoImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func addPicture(sender: AnyObject) {
if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
} else {
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion:nil)
}
}
}

Related

Swift - Use of unresolved identifier 'self' / Use of unresolved identifier 'Meme' / Use of unresolved identifier 'memedImage'

I get the error message Use of unresolved identifier 'self' as well as the error message Use of unresolved identifier 'Meme'; did you mean 'time'? and Use of unresolved identifier 'memedImage' in Xcode. I am trying to make a MemeMaker and am having trouble creating a struct for the modified image of the meme. Here is my code:
import UIKit
class ViewController: UIViewController,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
#IBOutlet weak var ImageView: UIImageView!
#IBOutlet weak var cameraButton: UIBarButtonItem!
#IBOutlet weak var topTextField: UITextField!
#IBOutlet weak var bottomTextField: UITextField!
let textFieldDelegate = TextFieldDelegate()
let memeTextAttributes:[NSAttributedString.Key: Any] = [
NSAttributedString.Key.strokeColor: UIColor.black,
NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-
CondensedBlack", size: 40)!,
NSAttributedString.Key.strokeWidth: -3.5]
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
topTextField.textAlignment = .center
bottomTextField.textAlignment = .center
topTextField.text = "Top Text"
bottomTextField.text = "Bottom Text"
if UIImagePickerController.isSourceTypeAvailable(.camera) {
cameraButton.isEnabled = true
} else {
cameraButton.isEnabled = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
//
UIImagePickerController().delegate = self
//
self.topTextField.delegate = textFieldDelegate
self.bottomTextField.delegate = textFieldDelegate
//
topTextField.defaultTextAttributes = memeTextAttributes
bottomTextField.defaultTextAttributes = memeTextAttributes
//
}
//Button to allow user pick an image from an Album
#IBAction func pickImageFromAlbum(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
//Allows user to use camera to take a photo
#IBAction func takeImageFromCamera(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
#objc internal func imagePickerController(_ picker:
UIImagePickerController, didFinishPickingMediaWithInfo info: [String:
Any]) {
if let pickedImage =
info[convertFromUIImagePickerControllerInfoKey
(UIImagePickerController.InfoKey.originalImage)] as? UIImage {
ImageView.contentMode = .scaleToFill
ImageView.image = pickedImage
dismiss(animated: true, completion: nil)
}
}
}
func generateMemedImage() -> UIImage {
// Render view to an image
UIGraphicsBeginImageContext(self.UIView.frame.size)
//Use of unresolved identifier 'self'
UIView.drawHierarchy(in: self.UIView.frame, afterScreenUpdates:
true) //Use of unresolved identifier 'self'
let memedImage:UIImage =
UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return memedImage
}
func save() {
// Creates the meme
let meme = Meme(topText: topTextField.text!, bottomText:
bottomTextField.text!, originalImage: UIImageView.image!, memedImage:
memedImage) //Use of unresolved identifier 'memedImage'
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input:
UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
you have declared function in outside of the class and try to saying that this identifier is belongs to current class but there is no class for that function
generateMemedImage()
Let's concentrate on just one of the many problems with your code — the issue with self.
This is the structure of your code. This is your code; all I did here was cut most of it, leaving the structure clearly visible:
class ViewController: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// ...
}
func generateMemedImage() -> UIImage {
UIGraphicsBeginImageContext(self.UIView.frame.size)
// ...
}
Your class declaration starts — and ends! Then comes a completely new function, func generateMemedImage. It is not inside the class declaration; it is just sitting out in the middle of nowhere. That's not illegal of itself; global functions are legal in Swift. But you cannot say self in a global function.
So the solution to that problem is to move the function inside the class declaration:
class ViewController: UIViewController,
UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// ...
func generateMemedImage() -> UIImage {
UIGraphicsBeginImageContext(self.UIView.frame.size)
// ...
}
}
I think I can help, I would first declare your Meme class or struct at the top of the page:
struct Meme {
let topText: String!
let bottomText: String!
let originalImage: UIImage!
let memedImage: UIImage!
}
Then you need to change:
memedImage: memedImage
to:
memedImage: generatedMemedImage()
Here is how you have it:
func save() {
// Creates the meme
let meme = Meme(topText: topTextField.text!, bottomText:
bottomTextField.text!, originalImage: UIImageView.image!, memedImage:
memedImage) //Use of unresolved identifier 'memedImage'
}
Here is the solution:
func save() {
// Creates the meme
let meme = Meme(topText: topTextField.text!, bottomText:
bottomTextField.text!, originalImage: UIImageView.image!, memedImage:
**generatedMemedImage()**)
}
I hope this helps.

Swift4 imagepicker giving me "Class 'viewcontroller' has no initializers"

I just started to learn swift and have almost no background on developing.
I'm making an app which involves image picker.
While making such function, I get this message saying Class 'viewcontroller' has no initializers.
How do I initialize viewcontroller?
I've searched other posts, but due to my lack of knowledge on developing languages, I'm having hard time understanding the solution.
Thanks in advance.
import UIKit
import MobileCoreServices
class viewcontroller: UIViewController, UINavigationControllerDelegate,
UIImagePickerControllerDelegate {
#IBOutlet var imgView: UIImageView!
let imagepicker: UIImagePickerController! = UIImagePickerController()
var captureimage: UIImage
var videoURL: URL!
var flagImageSave = false
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 btnCaptureImageFromCamera(_sender:UIButton) {
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
flagImageSave = true
imagepicker.delegate = self
imagepicker.sourceType = .camera
imagepicker.mediaTypes = [kUTTypeImage as String]
imagepicker.allowsEditing = false
present (imagepicker, animated: true, completion: nil)
}
}
#IBAction func btnLoadImageFromLibrary(_sender: UIButton) {
flagImageSave = false
imagepicker.delegate = self
imagepicker.sourceType = .photoLibrary
imagepicker.mediaTypes = [kUTTypeImage as String]
imagepicker.allowsEditing = true
present (imagepicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as NSString as String) {
captureimage = info[UIImagePickerControllerOriginalImage] as! UIImage
if flagImageSave {
UIImageWriteToSavedPhotosAlbum(captureimage, self, nil, nil)
}
imgView.image = captureimage
}
}
}
func btnCaptureImageFromCamera(_ sender: UIButton) {
}
func btnLoadImageFromLibrary(_ sender: UIButton) {
}
Firstly, style should be ViewController (not viewcontroller), and ideally more descriptive like TheImageViewController but anyway...
At a guess the issue is:
var captureimage: UIImage
Try:
var captureimage: UIImage?
As you have a non-primitive type, that is not ? or ! (read swift docs)
This happens because you declared captureimage property as non optional but haven't provided any instances of this property. To fix this you can either provide default value
var captureimage: UIImage = UIImage()
or make captureimage property optional
var captureimage: UIImage?

Insert an Image into PDF file Swift

I have searched a lot of pages but haven't seen any good explanation for making image to pdf. Also there are many never answered question. So it's looks helpful to ask here. The app has 'Camera', 'Photo Library' and 'Create PDF' buttons. After taken/choosing picture I want to attach this image into pdf file by 'Create PDF' button
Main Storyboard:
ViewController:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var PhotoLibrary: UIButton!
#IBOutlet weak var Camera: UIButton!
#IBOutlet weak var ImageDisplay: UIImageView!
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.
}
//MARK: Photo Library Button Action
#IBAction func PhotoLibraryAction(sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .PhotoLibrary
presentViewController(picker, animated: true, completion: nil)
}
//MARK: Camera Button Action
#IBAction func CameraAction(sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker, animated: true, completion: nil)
}
//MARK: Adding Texts on Selected/Taken Image
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if var image = info[UIImagePickerControllerOriginalImage] as? UIImage {
ImageDisplay.image = image
}
dismissViewControllerAnimated(true, completion: nil)
}
}
Use the following function to convert your image into pdf
func createPdfFromView(imageView: UIImageView, saveToDocumentsWithFileName fileName: String)
{
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, imageView.bounds, nil)
UIGraphicsBeginPDFPage()
let pdfContext = UIGraphicsGetCurrentContext()
if (pdfContext == nil)
{
return
}
imageView.layer.renderInContext(pdfContext!)
UIGraphicsEndPDFContext()
if let documentDirectories: AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
{
let documentsFileName = (documentDirectories as! String) + ("/\myPDFImage.pdf")
debugPrint(documentsFileName, terminator: "")
pdfData.writeToFile(documentsFileName, atomically: true)
}
}
I create pdf of a view, so I pass a UIView to this function. Pass your UIImageView to this function and it should work fine.

error: "Thread 1: EXC_BAD_ACCESS(Code=EXC_I386_GPFLT)

I need help here. I am trying to use core data to implement an app. But on line 52 -
myHood.setMyHoodImg(addHoodImg.image!))
I having an error each time a click the button to create a new hood. The error:
"Thread 1: EXC_BAD_ACCESS(Code=EXC_I386_GPFLT)
Here is the code:
import UIKit
import CoreData
class CreateHoodVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var hooddesc: UITextField!
#IBOutlet weak var addHoodImgBtn: UIButton!
#IBOutlet weak var addHoodImg: UIImageView!
var imagePicker: UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.delegate = self
addHoodImg.layer.cornerRadius = 4.0
addHoodImg.clipsToBounds = true
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
addHoodImg.image = image
}
#IBAction func addImage(sender: AnyObject!){
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func createHood(){
if let hoodDescription = hooddesc.text where hoodDescription != ""{
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("MyHood", inManagedObjectContext: context)!
let myHood = MyHood(entity: entity, insertIntoManagedObjectContext: context)
myHood.myHoodDescription = hoodDescription
myHood.setMyHoodImg(addHoodImg.image!)
context.insertObject(myHood)
do {
try context.save()
} catch {
print("Could not save new Hood")
}
}
}
}
it's really simple:
if You write:
myHood.setMyHoodImg(addHoodImg.image!)
you are supposing addHoodImg.image DOES exist, but on first run, is NIL, if You did not choose an image.
so 2 ways:
1) simply write:
if let hoodDescription = hooddesc.text where hoodDescription != "" , let img = addHoodImg.image {
2) disable button on start AND enable after choosing and image.
Hope this help.
ps I have a fully functional proto here with (reduced!) classes you use.

Swift: Thread 1 signal SIGABRT in class AppDelegate: UIResponder, UIApplicationDelegate

Whenever I try to open a different view controller with a show segue it crashes with this error Swift: Thread 1 signal SIGABRT in class AppDelegate: UIResponder, UIApplicationDelegate, I don't know why.
Here's the code of the View Controller that I try to open:
import UIKit
import CoreData
class AddEditVC: UIViewController, NSFetchedResultsControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var item : Item? = nil
#IBOutlet weak var itemName: UITextField!
#IBOutlet weak var imageHolder: UIImageView!
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
if item != nil {
itemName.text = item?.name
imageHolder.image = UIImage(data: (item?.image)!)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addImage(sender: AnyObject) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
pickerController.allowsEditing = true
self.presentViewController(pickerController, animated: true, completion: nil)
}
#IBAction func addImageFromCamera(sender: AnyObject) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.Camera
pickerController.allowsEditing = true
self.presentViewController(pickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
self.imageHolder.image = image
}
#IBAction func saveTapped(sender: AnyObject) {
if item != nil {
editItem()
} else {
createNewItem()
}
}
func createNewItem() {
let entityDescription = NSEntityDescription.entityForName("Item", inManagedObjectContext: moc)
let item = Item(entity: entityDescription!, insertIntoManagedObjectContext: moc)
item.name = itemName.text
item.image = UIImagePNGRepresentation(imageHolder.image!)
do {
try moc.save()
} catch {
return
}
}
func editItem () {
item?.name = itemName.text
item!.image = UIImagePNGRepresentation(imageHolder.image!)
do {
try moc.save()
} catch {
return
}
}
This error is usually appears when some of #IBOutlet or #IBAction is not assigned in the MainStoryboard.
Please check small circles before them. They should be grayed
It's either what Andriy is saying, or you executed a PerformSegueWithIdentifier(name, nil) with the wrong identifier. Best to add a screenshot of your storyboard & original controller as well to give a definite answer.
Good luck!

Resources