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

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.

Related

Getting error `Do you want to add protocol stubs? [duplicate]

This question already has answers here:
Xcode 8 says "Do you want to add a stub?" How do I answer?
(3 answers)
Closed 4 years ago.
I added the ImageView Protocol. What can be done to remove the error
Do you want to add protocol stubs?
CardsViewController
import UIKit
protocol ImageViewProtocol{
func sendImageToViewController(theImage: UIImage)
}
class CardsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImageViewProtocol {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var locationTextField: UITextField!
#IBOutlet weak var imageView: UIImageView!
#IBAction func goToViewController2Action(_ sender: Any)
{
let viewcontroller2 = storyboard?.instantiateViewController(withIdentifier: "viewController2") as! ViewController2
viewcontroller2.delegate = self
self.navigationController?.pushViewController(viewcontroller2, animated: true)
}
func chooseImagePickerAction(source: UIImagePickerController.SourceType) {
if UIImagePickerController.isSourceTypeAvailable(source) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = source
self.present(imagePicker, animated: true, completion: nil)
}
}
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
if nameTextField.text == "" || locationTextField.text == "" || textField.text == "" {
print("Not all fields are filled")
} else {
if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext {
let card = Card(context: context)
card.name = nameTextField.text
card.location = locationTextField.text
card.number = textField.text
if let image = imageView.image {
card.image = image.pngData()
}
do {
try context.save()
print("Cохранение удалось!")
} catch let error as NSError {
print("Не удалось сохранить данные \(error), \(error.userInfo)")
}
}
performSegue(withIdentifier: "unwindSegueFromNewCard", sender: self)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
imageView.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
}
ViewController2
import UIKit
class ViewController2: UIViewController {
var filter : CIFilter!
var delegate: ImageViewProtocol!
#IBOutlet weak var select: UISegmentedControl!
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var barcodeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
barcodeImageView.image = UIImage(named: "photo")
}
#IBAction func saveButtonAction(_ sender: Any) {
if textField.text == "" {
print("Not all fields are filled")
} else {
delegate.sendImageToViewController(theImage: barcodeImageView.image!)
self.navigationController?.popViewController(animated: true)
}
performSegue(withIdentifier: "unwindSegueFromViewController", sender: sender)
}
#IBAction func tappedEnter(_ sender: Any) {
if textField.text?.isEmpty ?? true {
return
} else {
if let texttxt = textField.text {
let data = texttxt.data(using: .ascii, allowLossyConversion: false)
if select.selectedSegmentIndex == 0
{
filter = CIFilter(name: "CICode128BarcodeGenerator")
} else {
filter = CIFilter(name: "CIQRCodeGenerator")
}
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 5, y: 5)
let image = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
barcodeImageView.image = image
}
}
}
}
This error comes because you implemented protocol (ImageViewProtcol) but you haven't add required methods of your protocol (in your case sendImageToViewController(theImage: UIImage)). All methods of your protocol are required by default. If you want to change it, you can look here.
It's the same as when you're implementing UITableViewDataSource, you also need to add required methods like number of items etc.
To fix this, add this method to your CardsViewController:
func sendImageToViewController(theImage: UIImage) {
// do something with image
}

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.

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

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

Resources