Dismiss Error In Project - ios

Im having an issue where I implement sort of a profile screen, where you can go to a settings screen and edit your picture. When I click the profile settings button it takes me too a screen where I can edit the profile. The Following Code contains the action that pushes that view controller
import UIKit
class ProfileeViewController: UIViewController {
let profileSetupTransition = AlterProfileViewController()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(profileFilledImage)
view.addSubview(profileeSettings)
navigationItem.title = "Profile"
///////////////////////////////////////////////////////////
//where all constraints f// constraints for the sign up label/title
_ = profileFilledImage.anchor(view.centerYAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 30, leftConstant: 25, bottomConstant: 0, rightConstant: 0, widthConstant: 15, heightConstant: 15)
//constraints for the sign up button
_ = profileeSettings.anchor(view.centerYAnchor, left: profileFilledImage.rightAnchor, bottom: nil, right: nil, topConstant: 30, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 140, heightConstant: 15)
///////////////////////////////////////////////////////////
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//will just be a nice looking image view to be next to the profile settings button
let profileFilledImage: UIImageView = {
let profileFilledImage = UIImageView()
profileFilledImage.image = UIImage(named: "icons8-User Filled-50")
profileFilledImage.clipsToBounds = true
profileFilledImage.translatesAutoresizingMaskIntoConstraints = false
profileFilledImage.contentMode = .scaleAspectFill
profileFilledImage.layer.masksToBounds = true
return profileFilledImage
}()
// will be the button that the user clicks to edit there profile settings
let profileeSettings: UIButton = {
let profileSetup = UIButton(type: .system)
profileSetup.setTitle("Profile Settings", for: .normal)
profileSetup.setTitleColor(.black, for: .normal)
profileSetup.addTarget(self, action: #selector(handleProfileSetuo), for: .touchUpInside)
return profileSetup
}()
func handleProfileSetuo(){
print("Profile Settings button tapped")
self.navigationController?.pushViewController(profileSetupTransition, animated: true)
//present(profileSetupTransition, animated: true, completion: nil)
}
}
Okay the following method handles selecting the image for the user's profile image. I use a UI Picker to select the image and than attempt to save it to a profile image view. When the picker dismisses it goes all the way back to the root view controller when it should go back to the page where I can continue to edit profile elements. The picture also does not change. Ive tried everything and nothing works. The code for that method is below
import UIKit
class AlterProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view?.backgroundColor = UIColor.white
navigationItem.title = "Profile Settings"
view.addSubview(selectProfileImage)
///Constraints for all views will go here
_ = selectProfileImage.anchor(view.centerYAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: -275, leftConstant: 135, bottomConstant: 0, rightConstant: 0, widthConstant: 100, heightConstant: 100)
// selectProfileImage.layer.cornerRadius = selectProfileImage.frame.size.width/2
///////////////////////////////////////////////
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
selectProfileImage.layer.cornerRadius = selectProfileImage.frame.size.width / 2;
selectProfileImage.layer.masksToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Where all buttons and labels will be added
//will just be a nice looking image view to be next to the profile settings button
lazy var selectProfileImage: UIImageView = {
let selectPicture = UIImageView()
// self.selectProfileImage.layer.cornerRadius = self.selectProfileImage.frame.size.width / 2;
selectPicture.image = UIImage(named: "Paris")
// selectPicture.layer.cornerRadius = selectPicture.frame.size.width / 2;
selectPicture.clipsToBounds = true
selectPicture.translatesAutoresizingMaskIntoConstraints = false
//selectPicture.layer.cornerRadius = selectPicture.frame.size.width/2
selectPicture.contentMode = .scaleAspectFill
selectPicture.isUserInteractionEnabled = true
selectPicture.layer.shouldRasterize = true
// will allow you to add a target to an image click
selectPicture.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView)))
selectPicture.layer.masksToBounds = true
return selectPicture
}()
func handleSelectProfileImageView(tapGestureRecognizer: UITapGestureRecognizer) {
print("123")
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
// will dispaly info of image selected
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("info")
var selectedImageFromPicker: UIImage?
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage{
print((editedImage as AnyObject).size)
selectedImageFromPicker = editedImage
self.selectProfileImage.image = selectedImageFromPicker
picker.dismiss(animated: true, completion: nil)
}else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage{
print((originalImage as AnyObject).size)
selectedImageFromPicker = originalImage
self.selectProfileImage.image = selectedImageFromPicker
picker.dismiss(animated: true, completion: nil)
}
/*
if let selectedImage = selectedImageFromPicker {
selectProfileImage.image = selectedImage
}
*/
/* dismiss(animated: true, completion: {
self.selectProfileImage.image = selectedImageFromPicker
}) */
}
// will handle the picker being closed/canceled
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("picker canceled")
dismiss(animated: true, completion: nil)
}
///////////////////////////////////////////////////////////////////////////////////
}

Wherever you are assigning imagePicker to UIImagePickerController,
you need to write this
func handleSelectProfileImageView(tapGestureRecognizer: UITapGestureRecognizer) {
print("123")
let picker = UIImagePickerController()
picker.delegate = self
picker.modalPresentationStyle = .overCurrentcontext //This is what I added
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}

Related

After Readed Barcode is not Opened ViewController Swift 3.0

I've created one storyboard with name Main1.storyboard and this storyboard have backend file with ViewController.swift name. All projects im created with Swift 3.0 . This storyboard is for reading barcode, i want to make after reading barcode to open homeViewController.xib - homeViewController.swift file and to send this barcode result. HomeViewController class have Webview components. For me is important just to open homeViewController.xib - homeViewController.swift file after reading barcode and send barcode result. My homeViewController.swift and ViewController.swift class is as given bellow:
homeViewController.swift:
import UIKit
import SystemConfiguration
import DrawerController
import SVProgressHUD
class homeViewController: UIViewController , UIWebViewDelegate,UIScrollViewDelegate {
var webView: UIWebView!
var text:String = "http://www.google.com"
var barcode:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// setup title
self.title = "My App"
// setup NavigationBar Color
self.navigationController?.navigationBar.barTintColor = navigationBarColor
let ud: UserDefaults = UserDefaults.standard
let data: NSData? = ud.object(forKey: "cookie") as? NSData
if let cookie = data {
let datas: NSArray? = NSKeyedUnarchiver.unarchiveObject(with: cookie as Data) as? NSArray
if let cookies = datas {
for c in cookies as! [HTTPCookie] {
HTTPCookieStorage.shared.setCookie(c)
}
}
}
// setup side Bar
if(sideBarPosition == "left"){
self.setupLeftMenuButton()
}
else{
self.setupRightMenuButton()
}
// setup WebView
webView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-64))
self.view.addSubview(webView)
webView.delegate = self
webView.scrollView.delegate = self
webView.isUserInteractionEnabled = false
SVProgressHUD.show()
if (typeOfData == "html"){
// load from html file
let myfile = Bundle.main.url(forResource: nameFileHtml, withExtension: "html")
let requestObj = NSURLRequest(url: myfile!)
webView.loadRequest(requestObj as URLRequest)
}
else{
// load website data
if(connectedToNetwork() == false){
SVProgressHUD.showError(withStatus: "No Internet Connection")
}
else{
webView.loadRequest(URLRequest(url: URL(string: text)!))
}
}
}
// setup left menu button icon
func setupLeftMenuButton() {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "menuleft.png")?.withRenderingMode(.alwaysTemplate), for: UIControlState.normal)
button.addTarget(self, action:#selector(leftDrawerButtonPress), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 17) //CGRectMake(0, 0, 30, 30)
button.imageView?.tintColor = iconColor
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
}
// setup left menu button action
func leftDrawerButtonPress(_ sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil)
}
// setup right menu button icon
func setupRightMenuButton() {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "menuright.png")?.withRenderingMode(.alwaysTemplate), for: UIControlState.normal)
button.addTarget(self, action:#selector(rightDrawerButtonPress), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 17) //CGRectMake(0, 0, 30, 30)
button.imageView?.tintColor = iconColor
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.rightBarButtonItem = barButton
}
// setup right menu button action
func rightDrawerButtonPress(_ sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.right, animated: true, completion: nil)
}
// setup webView option
func webViewDidStartLoad(_ webView: UIWebView)
{
SVProgressHUD.show()
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
if( barcode != "")
{
self.webView.stringByEvaluatingJavaScript(from:
"var element = document.getElementById('input-password');"
+ "element.value ="+barcode+";" +
"")
}
let cookieJar: HTTPCookieStorage = HTTPCookieStorage.shared
let data: NSData = NSKeyedArchiver.archivedData(withRootObject: cookieJar.cookies) as NSData
let ud: UserDefaults = UserDefaults.standard
ud.set(data, forKey: "cookie")
SVProgressHUD.dismiss()
webView.isUserInteractionEnabled = true
let aLabel = UIButton()
self.view.addSubview(aLabel)
aLabel.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
aLabel.heightAnchor.constraint(equalToConstant: 123.0).isActive = true
aLabel.setImage(UIImage(named: "photo-camera.png"), for: .normal)
aLabel.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = NSLayoutConstraint(item: aLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute:NSLayoutAttribute.trailing, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: aLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
aLabel.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint])
self.view.layoutIfNeeded()
}
#objc func buttonAction(sender: UIButton!) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main1", bundle: nil)
let balanceViewController = storyBoard.instantiateViewController(withIdentifier: "barcode") as! ViewController
self.present(balanceViewController, animated: true, completion: nil)
}
func btnclicked(sender: UIButton!)
{
let alert = UIAlertController(title: "Alert", message: "unwraped.stringValue", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if (scrollView.contentOffset.y < 0){
self.webView.reload()
}
}
// check connection
func connectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ViewController.swift
import UIKit
import AVFoundation
class ViewController: UIViewController,UIScrollViewDelegate , UIWebViewDelegate , AVCaptureMetadataOutputObjectsDelegate {
#IBOutlet weak var viewPreview: UIView!
var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer!
var isReading: Bool = false
var barcoderesult:String=""
#IBOutlet weak var anulo_btn: UIButton!
#IBAction func bnt_cancel(_ sender: Any) {
let vc = homeViewController(nibName: "homeViewController", bundle: nil)
let navigationController = UINavigationController(rootViewController: vc)
self.evo_drawerController?.setCenter(navigationController, withCloseAnimation: true, completion: nil)
self.dismiss(animated: true)
}
// setup left menu button icon
func setupLeftMenuButton() {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "menuleft.png")?.withRenderingMode(.alwaysTemplate), for: UIControlState.normal)
button.addTarget(self, action:#selector(leftDrawerButtonPress), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 17) //CGRectMake(0, 0, 30, 30)
button.imageView?.tintColor = iconColor
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
}
// setup left menu button action
func leftDrawerButtonPress(_ sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil)
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = navigationBarColor
// setup title
setupLeftMenuButton()
viewPreview.layer.cornerRadius = 5;
captureSession = nil;
if !isReading {
if (self.startReading()) {
}
}
else {
stopReading()
}
isReading = !isReading
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - IBAction Method
#IBAction func startStopClick(_ sender: UIButton) {
if !isReading {
if (self.startReading()) {
}
}
else {
stopReading()
}
isReading = !isReading
}
// MARK: - Custom Method
func startReading() -> Bool {
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession = AVCaptureSession()
captureSession?.addInput(input)
// Do the rest of your work...
} catch let error as NSError {
// Handle any errors
print(error)
return false
}
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer.frame = viewPreview.layer.bounds
viewPreview.layer.addSublayer(videoPreviewLayer)
/* Check for metadata */
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.metadataObjectTypes = captureMetadataOutput.availableMetadataObjectTypes
print(captureMetadataOutput.availableMetadataObjectTypes)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureSession?.startRunning()
return true
}
func stopReading() {
captureSession?.stopRunning()
captureSession = nil
videoPreviewLayer.removeFromSuperlayer()
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
for data in metadataObjects {
let metaData = data as! AVMetadataObject
print(metaData.description)
let transformed = videoPreviewLayer?.transformedMetadataObject(for: metaData) as? AVMetadataMachineReadableCodeObject
if let unwraped = transformed {
print(unwraped.stringValue)
// lblString.text = unwraped.stringValue
// btnStartStop.setTitle("Start", for: .normal)
barcoderesult = unwraped.stringValue
let alert = UIAlertController(title: "Alert", message: unwraped.stringValue, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
self.performSelector(onMainThread: #selector(stopReading), with: nil, waitUntilDone: false)
isReading = false;
}
}
}
}
It's difficult to answer your question without providing the error you gets when you run or what kind of error is listed in the console.
BTW, i guess you may haven't set the identifier for the viewController in each storyboards.

How to reload the data from UI picker view and close the Picker view with transition

class MainVC: UIViewController {
var datasourceForUsers :UserPicker!
var userPicker :UIPickerView!
var toolBar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
userPicker = UIPickerView()
toolBar = UIToolbar()
datasourceForUsers = UserPicker()
}
#IBAction func onMoreTapped(){
NotificationCenter.default.post(name: NSNotification.Name("ToggleSideMenu"), object: nil)
}
#IBAction func showRegisteredUsers(_ sender: Any) {
createUserPicker()
configureToolBar(toolBar)
}
func createUserPicker() {
userPicker.dataSource = datasourceForUsers
userPicker.delegate = datasourceForUsers
//Customizations
userPicker.backgroundColor = .black
userPicker.frame = CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 300)
self.view.addSubview(userPicker)
}
func configureToolBar(_ toolBar:UIToolbar ){
toolBar.sizeToFit()
toolBar.barTintColor = .black
toolBar.tintColor = .white
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(MainVC.dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
toolBar.frame = CGRect.init(x: 0.0, y: UIScreen.main.bounds.size.height - 300, width: UIScreen.main.bounds.size.width, height: 50)
self.view.addSubview(toolBar)
}
override func viewWillAppear(_ animated: Bool) {
userPicker.reloadAllComponents()
toolBar.reloadInputViews()
}
#objc func cancelDatePicker(){
self.view.endEditing(true)
}
#objc func dismissKeyboard() {
self.resignFirstResponder()
}
}
I used above code to show some data on UIPickerView .It works fine.But When I change the datasource(Add new Data) where the data is stored it does not reflect on the UI picker.In order to do that I have to run the application again.Second thing is I couldn't close the UI picker with transition.

imageview not updated accordingly

i want to create an imageview with photo selected from photo library and display in the scrollview by pushing a button. But the image is not displayed after selection but only display when I push the button again. Can someone help me with this one please?
#IBAction func imageBtnPressed(_ sender: Any) {
imagePicker()
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
func imagePicker(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let selectedImage = info[.originalImage] as? UIImage
imageOnCanvas = selectedImage
dismiss(animated: true, completion: nil)
}
Your code does not pause just because the UIImagePickerController is presented. So, let's look at your code:
#IBAction func imageBtnPressed(_ sender: Any) {
imagePicker()
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
func imagePicker(){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
So that is exactly like saying (substituting the contents of the imagePicker function for the function call):
#IBAction func imageBtnPressed(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
imageView.image = imageOnCanvas
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
}
Well, as you can clearly see, you are referring to imageOnCanvas when it has not been set yet. The imagePicker is still showing; the user has not chosen a photo yet. But your code has completely come to an end. You've gone on to add a subview consisting of the image view containing the image that was in imageOnCanvas before the code started.

Makpit Memory Leak

I tried a lot of solutions but even in actual device, memory consumption is very high. When secondview is dismissed first time, memory doesnot decrease like its increases. The memory usage after dismissing secondview depends on how much area user discovered in map.
Here is my code.
First view controller
import UIKit
import CoreLocation
class ViewController: UIViewController {
let manager = CLLocationManager()
private let currentColor = UIColor(red: 234/255.0, green: 128/255.0, blue: 16/255.0, alpha: 1.0)
override func viewDidLoad(){
super.viewDidLoad()
manager.requestWhenInUseAuthorization()
let button = buttonLoader(y: 7*self.view.frame.height/16, text: "trigger")
self.view.addSubview(button)
}
private func buttonLoader(y:CGFloat,text:String)->UIButton{
let Label = UIButton(frame: CGRect(x: 0, y: y , width: self.view.frame.width, height: self.view.frame.height/8))
Label.setTitle(text, for: .normal)
Label.addTarget(self, action: #selector(mapOpener), for: .touchUpInside)
Label.setTitleColor(currentColor, for: .normal)
self.view.addSubview(Label)
return Label
}
#objc func mapOpener(){
let newView = SecondViewController()
newView.view.backgroundColor = .white
self.present(newView, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
SecondViewController
import UIKit
import MapKit
class SecondViewController: UIViewController {
var map :MKMapView!
var saverButton : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
saveButtonLoader()
mapLoader()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapLoader(){
map = MKMapView(frame: CGRect(x: 0, y: 64, width: view.frame.size.width, height: self.view.frame.size.height-64))
map.mapType = MKMapType.standard
map.isZoomEnabled = true
map.isScrollEnabled = true
map.showsUserLocation = true
map.userTrackingMode = .follow
view.addSubview(map)
}
func saveButtonLoader() {
saverButton = UIButton(frame: CGRect(x: 4*view.frame.size.width/5, y: 20, width: view.frame.size.width/5, height: 44))
saverButton.setTitle("Finish", for: .normal)
saverButton.addTarget(self, action: #selector(finishButtonAction), for: UIControlEvents.touchUpInside)
saverButton.backgroundColor = UIColor.blue
saverButton.isEnabled = true
self.view.addSubview(saverButton)
}
override func viewWillDisappear(_ animated:Bool){
super.viewWillDisappear(animated)
self.applyMapViewMemoryFix()
}
func applyMapViewMemoryFix(){
map.delegate = nil
removeOldAnnotations()
map.removeFromSuperview()
map = nil
}
func removeOldAnnotations(){
for annotation in map.annotations{
map.removeAnnotation(annotation)
}
}
#objc func finishButtonAction(sender:UIButton!) {
self.dismiss(animated: true, completion: {
})
}
}

How to save only UIImageView not the whole screen in my photo app. In Swift

My app has a camera section. It takes a photo and then puts a watermark on the photo. However when the photo is saved, the whole screen is saved, not just the UIImageView. I just want the UIImageView to be saved. It's not that but because the menu bar at the button is not that big. I just think it would look better without the menu bar in the picture.
Photo of app just before taking photo:
Photo of how the picture taken is saved:
This is my code below.
import UIKit
class Camera: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var cameraScreen: UIImageView!
var screenView: UIImageView!
#IBAction func Camera(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)}}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject: AnyObject]!){
cameraScreen.image = image
self.dismiss(animated: true, completion: nil);
screenView = UIImageView()
screenView.frame = CGRect(x:0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
let text = "Java"
let label = UILabel(frame: CGRect(x: 125, y: 400, width: self.view.frame.width, height: 300))
label.font = UIFont(name: label.font.fontName, size: 200)
label.textColor = UIColor.blue
label.alpha = 0.3
label.text = text
self.view.addSubview(screenView)
self.view.addSubview(label)
// i tried self, nil, nil
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.drawHierarchy(in: self.view.bounds, afterScreenUpdates: true)
let photo = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(photo!, nil, nil, nil)
}
#IBAction func Save(_ sender: AnyObject) {
let alert = UIAlertController(title: "Image Saved", message: "", preferredStyle: .alert)
let okay = UIAlertAction(title: "OK.", style: .default, handler: nil)
alert.addAction(okay)
present(alert, animated: true, completion: nil)
}
}

Resources