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.
Related
converted app from swift 3 to swift 4.2.
my app had a upload your profile image feature that is not working anymore and I am trying to figure out why. For now What I see is that
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo
didFinishPickingMediaWithInfo Is not being called after media was chosen
Here is my views full code:
import UIKit
class CameraMenuViewController: BaseViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var UserID:Int = 0
#IBOutlet weak var myImageView: UIImageView!
var callback : ((UIImage) -> ())?
#IBOutlet weak var btn_end: UIButton!
#IBOutlet weak var from_camera: UIBarButtonItem!
#IBOutlet weak var from_gallery: UIBarButtonItem!
#IBAction func btn_end_pressed(_ sender: UIButton) {
//
//self.openViewControllerBasedOnIdentifier("Home")
//let data = UIImagePNGRepresentation(myImageView) as NSData?
let image = myImageView.image!.pngData() as NSData?
//if let data = UIImagePNGRepresentation(myImageView) {
print("callback data")
let userDetails:Dictionary = (UserDefaults.standard.value(forKey: "myUserDetails") as? [String:Any])!
let UserID:Int = userDetails["UserID"] as! Int
print("UserID")
print(UserID)
print("is_selfie from callback")
//save profile image as NewUserID
UserDefaults.standard.set(image, forKey: String(UserID))
UserDefaults.standard.synchronize()
self.view.removeFromSuperview()
//}
}
#IBAction func btn_closer(_ sender: UIButton) {
//self.view.removeFromSuperview()
}
#IBAction func photofromLibrary(_ sender: UIBarButtonItem) {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
picker.modalPresentationStyle = .popover
present(picker, animated: true, completion: nil)
picker.popoverPresentationController?.barButtonItem = sender
}
#IBAction func shootPhoto(_ sender: UIBarButtonItem) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
print("photo shoot")
//UserDefaults.standard.set("selfie", forKey: "is_selfie")
UserDefaults.standard.set(true, forKey: "is_selfie")
UserDefaults.standard.synchronize()
DispatchQueue.main.async {
self.picker.allowsEditing = false
self.picker.sourceType = UIImagePickerController.SourceType.camera
self.picker.cameraCaptureMode = .photo
self.picker.modalPresentationStyle = .fullScreen
self.present(self.picker,animated: true,completion: nil)
}
} else {
noCamera()
}
}
let picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
picker.delegate = self
DispatchQueue.global(qos: .userInitiated).async
{
self.present(self.picker, animated: true, completion: nil)
}
let language = UserDefaults.standard.object(forKey: "myLanguage") as! String
if(language=="arabic"){
//from_camera.setTitle("كاميرا",for: .normal)
//from_gallery.text.setTitle("الصور",for: .normal)
btn_end.setTitle("إنهاء",for: .normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Delegates
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
let chosenImage = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as! UIImage //2
myImageView.contentMode = .scaleAspectFit //3
myImageView.image = chosenImage //4
myImageView.layer.borderWidth = 1
myImageView.layer.masksToBounds = false
myImageView.layer.borderColor = UIColor.black.cgColor
myImageView.layer.cornerRadius = myImageView.frame.height/4
myImageView.clipsToBounds = true
callback?(chosenImage)
dismiss(animated:true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .alert)
let okAction = UIAlertAction(
title: "OK",
style:.default,
handler: nil)
alertVC.addAction(okAction)
present(
alertVC,
animated: true,
completion: nil)
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
return input.rawValue
}
Please help me understand why didFinishPickingMediaWithInfo isn't getting called anymore
It appears as though the function declaration changed between Swift 3 and 4.2. This mustn't have been updated for you by the Swift Migrator Tool. One trick I do when this happens, to check what the correct function declaration is, is to use multiline comment syntax to comment out your current function (didFinishPickingMediaWithInfo in your case). Then you can start typing the function out again, and use Xcode autocomplete to ensure you have it correct. You can then copy the contents of the function you commented out to this new and correct function declaration.
Or - you could just look it up the documentation! According to the documentation on imagePickerController, the function should be declared as:
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
If you replace your function declaration with the above, it should get called again.
As Craig said you need to change delegate function declaration and also afterwards you need to update the following:
let chosenImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
These two changes combined should solve your issue.
i think the name off the function is update
this is my code in My app And work greate
extension FCViewController: UIImagePickerControllerDelegate
{
internal func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
if let photo = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}
// Any Code Here ...
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?
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)
}
}
}
I am trying to make a simple "Profile" view that allows the user to change his picture. the image picker loads the gallery successfully and i choose the new image then write it to documents directory to load it in next launch, the problem is the imageview is not refreshing with the new image until i exit the app and relaunch again (only viewDidLoad works but viewWillAppear is loading the old image although it is overwritten!) any ideas?
import UIKit
class Profile: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var imagePicker:UIImagePickerController=UIImagePickerController()
var pickedImage:UIImage?
let filemgr = NSFileManager.defaultManager()
#IBOutlet weak var profilepic: UIImageView!
#IBOutlet weak var lblheight: UILabel!
#IBOutlet weak var lblwidth: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
profilepic.layer.borderWidth=1
profilepic.layer.borderColor=UIColor.blackColor().CGColor
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
profilepic.userInteractionEnabled = true
profilepic.addGestureRecognizer(tapGestureRecognizer)
imagePicker.delegate=self
if profileImageExists()
{
pickedImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))!
} else {
pickedImage=UIImage(named:"camera.png")!
}
profilepic.image=pickedImage
}
func imageTapped(img: AnyObject)
{
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion:
{
self.lblheight.text="completed"
print ("completed image tab")
}
)
}
override func viewWillAppear(animated: Bool) {
pickedImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))!
profilepic.image=pickedImage
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
profilepic.contentMode = .ScaleToFill
profilepic.image = pickedImage
if let data = UIImagePNGRepresentation(pickedImage) {
let filename = Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png")
data.writeToFile(filename, atomically: true)
}
}
dismissViewControllerAnimated(true, completion: nil)
}
func profileImageExists() -> Bool
{
if let profileImage=UIImage(named: Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png"))
{
return true
}
else
{
return false
}
}
}
Loading an UIImage with init(named:) caches the image. So as long as the image name does not change or the system is emptying the cache (for example when you restart the app) the image will be used from the cache and not loaded again.
Try to use init(contentsOfFile:) instead to load the image.
Try updating your imagePickerController method. You have used pickedImage as an instance variable and an local optional variable. I have used newImage instead.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let newImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
profilepic.contentMode = .ScaleToFill
profilepic.image = newImage
pickedImage = newImage
if let data = UIImagePNGRepresentation(newImage) {
let filename = Operations.getDocumentsDirectory().stringByAppendingPathComponent("profile.png")
data.writeToFile(filename, atomically: true)
}
}
dismissViewControllerAnimated(true, completion: nil)
}
In the app that i am making, the user will select a photo, then it will appear in the imageview. How do i save the image that they selected in the image.xcassets folder, so when i relaunch the app, the image will still be there?
Here is the code that i am using...
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: 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.
}
#IBAction func Action(sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
let imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
self.dismissViewControllerAnimated(true, completion: nil)
self.imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
//how do i save the image in the folder?
}
}
You can do so by doing this
var finalImage : UIImage()
//Your Method
func saveImage () {
self.imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.finalImage = self.imageView.image as UIImage
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
let readPath = dirPath.stringByAppendingPathComponent("Image.png")
let image = UIImage(named: readPath)
let writePath = dirPath.stringByAppendingPathComponent("Image2.png")
UIImagePNGRepresentation(self.finalImage).writeToFile(writePath, atomically: true)
}
}
}
}