I can call so imagePicker that the program is waiting for image selection - swift3

my delegate always returns nil for my image in custom table cell.
PhotoTakingHelper just class for imagepicker setting.
How i can pausing programm for pick image?
Method in CustomCell class:
#IBAction func loadImageButtonTapped(_ sender: UIButton) {
loadingImage=true
if delegate != nil {
let (image,name) = delegate.loadImageForQuestionAction(question: question)
print("Delegate return \(image)")
imageInCreatingCell = image
nameInCreatingCell = name
//loadImageButton.isHidden = true
}
}
Method in tableView class:
func loadImageForQuestionAction(question: Question) -> (UIImage?,String?) {
var returnImage:UIImage?
var returnName:String?
self.photoTakingHelper=PhotoTakingHelper(viewcontroller: self, callback: { (image:UIImage?,name:String?) in
if let photoImage = image {
print(photoImage)
print(name)
returnImage=photoImage
returnName=name
//NEED SHOWING IMAGE NAME HOW LABEL
print("loadImageAction")
}
})
return (returnImage,returnName)
}
Method in PhotoTakingHelper:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//viewController.dismiss(animated: false, completion: nil)
categoryViewController.dismiss(animated: false, completion: nil)
var fileName:String? = nil
if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
fileName = result.firstObject?.value(forKey: "filename") as! String?
}
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
callBack(image,fileName)
} else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
callBack(image,fileName)
} else {
print("Something went wrong")
callBack(nil,nil)
}
}

UPDATE:
func loadImageForQuestionAction(question: Question, completion: #escaping (UIImage?, String?) -> ()) {
var returnImage:UIImage?
var returnName:String?
self.photoTakingHelper=PhotoTakingHelper(viewcontroller: self, callback: { (image:UIImage?,name:String?) in
DispatchQueue.main.async {
if let photoImage = image {
print(photoImage)
print(name)
returnImage=photoImage
returnName=name
completion(returnImage,returnName)
//NEED SHOWING IMAGE NAME HOW LABEL
print("loadImageAction")
} else {
completion(returnImage,returnName)
}
}
})
}

Related

Creating an image format with an unknown type is an error UIImagePickerController() , unexpectedly found nil

Swift Version 3
Xcode Version 8.3.3 (8E3004b)
This question has been asked and answered before. Yet, I cannot find a way fix this error.
"Creating an image format with an unknown type is an error" with UIImagePickerController
When a new picture is selected from Photo Library, I get this error
Generic Creating an image format with an unknown type is an error.
I select the photo and when I tap choose, I get error in func takePhoto where I do this assignment self?.imgView.image = newImage
fatal error: unexpectedly found nil while unwrapping an Optional value
Printing description of newImage: expression produced error: error:
/var/folders/s0/xq_zc7l56m1__n1qjk29p6tw0000gn/T/./lldb/2631/expr1.swift:1:80:
error: use of undeclared type 'UIKit'
Swift._DebuggerSupport.stringForPrintObject(Swift.UnsafePointer>(bitPattern:
0x118055200)!.pointee)
^~~~~
typealias imagePickerHelperCompletion = ((UIImage?) -> Void)!
class ImagePickerHelper: NSObject {
weak var viewController: UIViewController!
var cameraFlashMode: UIImagePickerControllerCameraFlashMode //flash, no flash
var photoLibraryIsVisible: Bool
var cameraDevice: UIImagePickerControllerCameraDevice //front, back camera
var completion: imagePickerHelperCompletion
init(viewController: UIViewController, cameraFlashMode:UIImagePickerControllerCameraFlashMode, photoLibraryIsVisible: Bool,cameraDevice: UIImagePickerControllerCameraDevice, completion: imagePickerHelperCompletion) {
self.viewController = viewController
self.completion = completion
self.cameraFlashMode = cameraFlashMode
self.photoLibraryIsVisible = photoLibraryIsVisible
self.cameraDevice = cameraDevice
//super.init() implemented by subclasses to initializer a new object (the receiver) immediately after memory has been allocated
super.init()
self.showPhotoSourceSelection()
}
//show camera or photo library
func showPhotoSourceSelection() {
let actionSheet = UIAlertController(title: "Take new photo", message: "Would you like to open \n Camera or Photo Library?", preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: .default) { (action) in
self.showImagePicker(sourceType: .camera)
}
let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .default) { (action) in
self.showImagePicker(sourceType: .photoLibrary)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in }
actionSheet.addAction(cameraAction)
if photoLibraryIsVisible == true { actionSheet.addAction(photoLibraryAction) }
actionSheet.addAction(cancelAction)
viewController.present(actionSheet, animated: true, completion: nil)
}
func showImagePicker(sourceType: UIImagePickerControllerSourceType) {
let imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true //user can crop the image, or do some editing
imagePicker.sourceType = sourceType
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.delegate = self
if imagePicker.sourceType == .camera {
imagePicker.cameraFlashMode = cameraFlashMode
imagePicker.cameraDevice = self.cameraDevice
}
viewController.present(imagePicker, animated: true, completion: nil)
}
}//end of class
extension ImagePickerHelper: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
viewController.dismiss(animated: true, completion: nil)
}
//if user did take a photo
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print(info)
//prints out ["UIImagePickerControllerEditedImage": <UIImage: 0x610000294320> size {746, 498} orientation 0 scale 1.000000, "UIImagePickerControllerMediaType": public.image, "UIImagePickerControllerCropRect": NSRect: {{0, 0}, {2661, 1779}}, "UIImagePickerControllerReferenceURL": assets-library://asset/asset.JPG?id=ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED&ext=JPG, "UIImagePickerControllerOriginalImage": <UIImage: 0x610000299320> size {2668, 1780} orientation 0 scale 1.000000]
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
completion(image)
viewController.dismiss(animated: true, completion: nil)
} else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
viewController.dismiss(animated: true, completion: nil)
completion(image)
} else {
print("something is wrong line \(#line)")
}
}
}//end of extension
class ProfileViewController: UITableViewController {
var imagePickerHelper: ImagePickerHelper!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func takePhoto(_ sender: Any) {
//create instance of ImagePickerHelper and take photo, or get it from photoLibrary
imagePickerHelper = ImagePickerHelper( viewController: self, cameraFlashMode: .auto,photoLibraryIsVisible: true, cameraDevice: .front,
completion: { [weak self] (newImage) in
})
}
}//end of class

Presenting image picker using TapGesture on UIImageView

I have a View with an UIImageView that I want to be 'selectable' so that the user can pick a new image.
The function for picking the new image is in the Controller.
Question
How do I call the myDatasourceController.handleTap() function by pressing the ImageView, so that the image picker is presented?
This is an example of my current setup
View
class myView: UICollectionViewCell {
lazy var profileImageView: UIImageView = {
let iv = UIImageView()
iv.isUserInteractionEnabled = true
iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(myDatasourceController.handleTap)))
return iv
}()
}
Controller
class myDatasourceController: UICollectionViewController,
UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
func handleTap(){
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// logic for picking the image
dismiss(animated: true, completion: nil)
}
}
This setup currently throws the error
unrecognized selector sent to instance 0x7f9163d493f0
which has led me to try various combinations of
handleTap(_:)
handleTap(sender: UITapGestureRecogniser)
/// etc
but I can't get any of them to work. How should I be constructing my View, Controller, and the interaction between them to present the image picker?
Use Like this
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(RegisterViewController. handleTap(gesture:)))
func handleTap(gesture: UIGestureRecognizer) {
// if the tapped view is a UIImageView then set it to imageview
if (gesture.view as? UIImageView) != nil {
print("Image Tapped")
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
present(picker, animated: true, completion: nil)
}
}
Use like this :
myDatasourceController.handleTap()
In your code :
iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(myDatasourceController.handleTap())))
The key to the solution is to implement a protocol / delegate, as suggested by #Akis
I've uploaded the full project to my github account. The key code is copied here.
View Controller
protocol ImagePickerDelegate: class {
func loadImagePicker()
}
class HomeViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImagePickerDelegate {
let cellId = "cellId"
func loadImagePicker(){
print(" -- image picker -- ")
// load image picker
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// get the image
var selectedImageFromPicker: UIImage?
if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
selectedImageFromPicker = editedImage
}else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker {
//doSomethingWithTheImage(image: selectedImage)
}
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .black
collectionView?.register(HomeView.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomeView
cell.delegate = self
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
}
View
class HomeView: UICollectionViewCell {
// break retain cycle with weak var
weak var delegate: ImagePickerDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
lazy var profileImageView: UIImageView = {
let iv = UIImageView()
iv.isUserInteractionEnabled = true
iv.image = UIImage(named: "kuang-si-falls-waterfall-water-laos-50588.jpg")
iv.contentMode = .scaleAspectFill
let tap = UITapGestureRecognizer(target: self, action: #selector(loadImagePicker))
iv.addGestureRecognizer(tap)
return iv
}()
func loadImagePicker() {
delegate?.loadImagePicker()
print(" imagePickerProtocol called ")
}
func setupViews() {
backgroundColor = .white
addSubview(profileImageView)
profileImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
profileImageView.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

Image capture from camera and gallery in swift

I am trying to get image from camera and show in imageview using swift 3.0 but it is showing white background only. Image is uploaded to my server successfully. On iPAD it is not even opening the camera app. below is my code: I am new to swift to please let me know what mistake i ma doing.
import UIKit
import Alamofire
import SwiftyJSON
import AlamofireImage
class RadiologyViewController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate{
#IBOutlet weak var indicator1: UIActivityIndicatorView!
#IBOutlet weak var name : UILabel!
#IBOutlet weak var mobile: UILabel!
#IBOutlet weak var gender: UILabel!
#IBOutlet weak var age : UILabel!
#IBOutlet weak var indicator4: UIActivityIndicatorView!
#IBOutlet weak var indicator3: UIActivityIndicatorView!
#IBOutlet weak var indicator2: UIActivityIndicatorView!
#IBOutlet weak var pic4text: UITextView!
#IBOutlet weak var pic3text: UITextView!
#IBOutlet weak var pic2text: UITextView!
#IBOutlet weak var pictext1: UITextView!
// WHICH SHOW BUTTON YOU WANT TO SHOW YOU HAVE TO CHANGE HEIGHT CONSTRAINT //
// conPic1height = conPic1height - 20 - UN HIDE BUTTON BY TAKING ITS OUTLET//
#IBOutlet weak var conPic1height: NSLayoutConstraint!
#IBOutlet weak var conPic2height: NSLayoutConstraint!
#IBOutlet weak var conPic3height: NSLayoutConstraint!
#IBOutlet weak var conPic4height: NSLayoutConstraint!
#IBOutlet weak var pic4: UIImageView!
#IBOutlet weak var pic3: UIImageView!
#IBOutlet weak var pic2: UIImageView!
#IBOutlet weak var pic1: UIImageView!
#IBOutlet weak var complain: UILabel!
#IBOutlet weak var explain : UILabel!
#IBOutlet weak var date : UILabel!
#IBOutlet weak var btnShowPic4: UIButton!
#IBOutlet weak var btnShowPic3: UIButton!
#IBOutlet weak var btnShowPic2: UIButton!
#IBOutlet weak var btnShowPic1: UIButton!
var patient : Patients? = nil;
var username : String? = nil;
var picNumber : Int = 0;
var pic1path : String = "";
var pic2path : String = "";
var pic3path : String = "";
var pic4path : String = "";
var strLabel = UILabel()
var indicator = UIActivityIndicatorView()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.isNavigationBarHidden = true
if patient != nil {
name.text = patient?.patientName;
age.text = "Age: "+(patient?.patientAge)!;
gender.text = "Gender: "+(patient?.patientGender)!;
mobile.text = "Mobile: "+(patient?.patientMobile)!;
date.text = "Date: "+(patient?.patientDate)!;
complain.text = "Complaint: " + "\(self.makeComplainText(complain: (patient?.patientComplaint)!))";
explain.text = "Explain: "+(patient?.patientExplainComplaint)!;
}
let defaults1 = UserDefaults.standard
let user = defaults1.object(forKey: "user") as? NSData
let responseData = NSKeyedUnarchiver.unarchiveObject(with: user! as Data) as? ResponseModel
if responseData != nil {
if responseData?.profile != nil {
username = responseData?.profile[0].userName;
}
}
pictext1.delegate = self
pic2text.delegate = self
pic3text.delegate = self
pic4text.delegate = self
pic1path = (patient?.patientPic1)!;
pic2path = (patient?.patientPic2)!;
pic3path = (patient?.patientPic3)!;
pic4path = (patient?.patientPic4)!;
pictext1.text = patient?.patientPictxt1;
pic2text.text = patient?.patientPictxt2;
pic3text.text = patient?.patientPictxt3;
pic4text.text = patient?.patientPictxt4;
let tapFirstGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped1(_:)))
pic1.isUserInteractionEnabled = true
pic1.addGestureRecognizer(tapFirstGestureRecognizer)
let tapSecondGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped2(_:)))
pic2.isUserInteractionEnabled = true
pic2.addGestureRecognizer(tapSecondGestureRecognizer)
let tapThirdGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped3(_:)))
pic3.isUserInteractionEnabled = true
pic3.addGestureRecognizer(tapThirdGestureRecognizer)
let tapFourGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped4(_:)))
pic4.isUserInteractionEnabled = true
pic4.addGestureRecognizer(tapFourGestureRecognizer)
if patient?.patientPic1 != "" {
pic1.image = nil;
setImage(imageview: pic1, url: (patient?.patientPic1)!,indicator:indicator1)
showFirstButton(show: false)
} else {
showFirstButton(show: true)
indicator1.isHidden = true
}
if patient?.patientPic2 != "" {
pic2.image = nil;
showSecondButton(show: false)
setImage(imageview: pic2, url: (patient?.patientPic2)!,indicator:indicator2)
} else {
showSecondButton(show: true)
indicator2.isHidden = true
}
if patient?.patientPic3 != "" {
pic3.image = nil;
showThreeButton(show: false)
setImage(imageview: pic3, url: (patient?.patientPic3)!,indicator:indicator3)
} else {
showThreeButton(show: true)
indicator3.isHidden = true
}
if patient?.patientPic4 != "" {
pic4.image = nil;
showFourButton(show: false)
setImage(imageview: pic4, url: (patient?.patientPic4)!,indicator:indicator4)
} else {
showFourButton(show: true)
indicator4.isHidden = true
}
let tapKeuboardDismissGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard(_:)))
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tapKeuboardDismissGestureRecognizer)
// Do any additional setup after loading the view.
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" // Recognizes enter key in keyboard
{
textView.resignFirstResponder()
return false
}
return true
}
func dismissKeyboard(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
}
func imageTapped1(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 1;
showActionSheet()
}
}
func imageTapped2(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 2;
showActionSheet()
}
}
func imageTapped3(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 3;
showActionSheet()
}
}
func imageTapped4(_ sender: UITapGestureRecognizer) {
if (sender.view as? UIImageView) != nil {
print("Image Tapped")
picNumber = 4;
showActionSheet()
}
}
func camera()
{
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.allowsEditing = false
myPickerController.sourceType = UIImagePickerControllerSourceType.camera
myPickerController.cameraCaptureMode = .photo
myPickerController.modalPresentationStyle = .fullScreen
self.present(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
// if (UIDevice.current.userInterfaceIdiom == .pad) {
// let popover = actionSheet.popoverPresentationController
// popover?.sourceRect = self.view.bounds
// popover?.sourceView = self.pic1
// popover?.permittedArrowDirections = .any
// self.present(actionSheet, animated: true, completion: nil)
// } else {
self.present(actionSheet, animated: true, completion: nil)
//}
}
#IBAction func btnpic3Click(_ sender: Any) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic3path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic4Click(_ sender: Any) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic4path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic1Click(_ sender: UIButton) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic1path
self.present(viewcontroller, animated: false)
}
#IBAction func btnpic2Click(_ sender: UIButton) {
var profileStoryBoard: UIStoryboard!
profileStoryBoard = UIStoryboard(name:"\(Helper.manageStoryBoardName())ShowImage",bundle: nil)
let viewcontroller : ImageShowViewController = profileStoryBoard.instantiateViewController(withIdentifier: "ImageShowViewController") as! ImageShowViewController
viewcontroller.url = pic2path
self.present(viewcontroller, animated: false)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if picNumber == 1 {
pic1.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else if picNumber == 2 {
pic2.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else if picNumber == 3 {
pic3.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
} else {
pic4.image = info[UIImagePickerControllerOriginalImage] as? UIImage
uploadImage(image: (info[UIImagePickerControllerOriginalImage] as? UIImage)!)
}
self.dismiss(animated: true, completion: nil)
}
func uploadImage(image:UIImage) -> Void {
if Reachability.isConnectedToNetwork() == true {
self.showLoading(title: "uploding image");
let imgData = UIImageJPEGRepresentation(image, 0.2)!
var path :String = "";
let parameters = ["username": username]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "images",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key)
}
},
to:"http://www.dentalsa.net/api/api.php?method=radiaolog_image_update")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
self.hideLoading()
let value = response.result.value
let jsonResponse = JSON(value)
let status = jsonResponse["status"].stringValue
let message = jsonResponse["message"].stringValue
if status == "false" {
self.showAlerError(titleText: "Error", messagetext: message);
}
path = jsonResponse["path"].stringValue
if self.picNumber == 1 {
self.pic1path = path
} else if self.picNumber == 2 {
self.pic2path = path
} else if self.picNumber == 3 {
self.pic3path = path
} else if self.picNumber == 4 {
self.pic4path = path
}
print("ImagePath"+path)
}
case .failure(let encodingError):
print(encodingError)
}
}
} else {
self.showAlerError(titleText: "Error", messagetext: "Please check Internet connectivity");
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func makeComplainText(complain:String) -> String {
let characters = Array(complain.characters);
var data="";
if characters[0] == "1" {
data += "Check-Up, ";
}
if characters[1] == "1" {
data += "Teeth Cleaning, ";
}
if characters[2] == "1" {
data += "Periodontal Treatment, ";
}
if characters[3] == "1" {
data += "Dental Fillings, ";
}
if characters[4] == "1" {
data += "Prothesis, ";
}
if characters[5] == "1" {
data += "Extraction, ";
}
if characters[6] == "1" {
data += "Hollywoods smile, ";
}
if characters[7] == "1" {
data += "Children's Teeth, ";
}
if characters[8] == "1" {
data += "Bleaching, ";
}
return data;
}
#IBAction func saveClick(_ sender: UIButton) {
let netowrk = NetworkCall();
if Reachability.isConnectedToNetwork() == true {
self.showLoading(title: "Please wait")
netowrk.radiologyUpdate(username: username!,patientId: (patient?.patientID)!,picText1: pictext1.text!,picText2: pic2text.text!,picText3: pic3text.text!,picText4: pic4text.text!,pic1:pic1path,pic2:pic2path,pic3:pic3path,pic4:pic4path) { responseObject in
self.hideLoading()
if responseObject.status == "true" {
print("Success view controller");
self.showAlerError(titleText: "Success", messagetext: "Details saved Successfully");
} else {
self.showAlerError(titleText: "Error", messagetext: responseObject.message!);
}
return
}
} else {
self.showAlerError(titleText: "Error", messagetext: "Please check Internet connectivity");
}
}
func showLoading(title: String) {
strLabel.removeFromSuperview()
indicator.removeFromSuperview()
effectView.removeFromSuperview()
strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
strLabel.text = title
strLabel.font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightMedium)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
indicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
indicator.startAnimating()
effectView.addSubview(indicator)
effectView.addSubview(strLabel)
view.addSubview(effectView)
}
func setImage(imageview :UIImageView,url:String,indicator:UIActivityIndicatorView) -> Void {
Alamofire.request("http://www.dentalsa.net"+url).responseImage { response in
if let image = response.result.value {
indicator.isHidden = true
imageview.image = image
}
}
}
func hideLoading() {
self.effectView.removeFromSuperview()
//indicator.stopAnimating()
}
func showAlerError(titleText:String,messagetext:String) {
let alertController = UIAlertController(title: titleText, message:
messagetext, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
#IBAction func backClick(_ sender: UIButton) {
_ = self.navigationController?.popViewController(animated: true)
}
func showFirstButton(show :Bool){
//conPic1height.constant = 150
btnShowPic1.isHidden = show
self.view.layoutIfNeeded()
}
func showSecondButton(show :Bool){
//conPic1height.constant = 150
btnShowPic2.isHidden = show
self.view.layoutIfNeeded()
}
func showThreeButton(show :Bool){
//conPic1height.constant = 150
btnShowPic3.isHidden = show
self.view.layoutIfNeeded()
}
func showFourButton(show :Bool){
//conPic1height.constant = 150
btnShowPic4.isHidden = show
self.view.layoutIfNeeded()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I need to capture image from camera and gallery on both iphone and iPad. I don't know what is the issue which i am facing here.

UILabel data to UIAlert issue in xcode 8, error

I made an alert and I tried to follow a tutorial and put it into my code. I put the code in a few different places but the errors just kept getting worse. I finally just put it at the bottom, because thats where I ended up getting the fewest errors. I'm new to xcode so this very basic thing is very hard for me. Furthermore, I get errors all over the place when I put this in, and I have no idea how to fix this. Moreover, what I am trying to do is take the data that is being saved in my UILabel which is a name, and I want that to be shown up in the clickable part of the alert that "dismisses" the alert, but I have no idea how to do that or even get started when I can't add a basic alert into my code. Any help would be great source code even better. Sorry for all the questions. Thanks again in advance.
import UIKit
import MultipeerConnectivity
class ViewController: UIViewController, MCBrowserViewControllerDelegate {
#IBOutlet weak var input: UITextField!
#IBOutlet weak var output: UILabel!
#IBAction func action(_ sender: Any) {
output.text = input.text
UserDefaults.standard.set(input.text, forKey: "MyName")
input.text = ""
}
var currentPlayer:String!
var appDelegate:AppDelegate!
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.MPCHandler.setupPeerWithDisplayName(UIDevice.current.name)
appDelegate.MPCHandler.setupSession()
appDelegate.MPCHandler.advertiseSelf(true)
NotificationCenter.default.addObserver(self, selector: Selector(("peerChangedStateWithNotification:")), name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: Selector(("handleReceivedDataWithNotification:")), name: NSNotification.Name(rawValue: "MPC_DidReceiveDataNotification"), object: nil)
}
#IBAction func connect(_ sender: Any) {
if appDelegate.MPCHandler.session != nil{
appDelegate.MPCHandler.setupBrowser()
appDelegate.MPCHandler.browser.delegate = self
self.present(appDelegate.MPCHandler.browser, animated: true, completion: nil)
}
}
func peerChangedStateWithNotification(notification:NSNotification){
let userInfo = NSDictionary(dictionary: notification.userInfo!)
let state = userInfo.object(forKey: "state") as! Int
if state != MCSessionState.connecting.rawValue{
self.navigationItem.title = "Connected"
}
}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
if let x = UserDefaults.standard.object(forKey:"myName") as?
String
{
output.text = x
}
}
}
func viewDidAppear(_animated: Bool) {
createAlert(title: "HI", message: "ARE YOU READY")
}
func createAlert (title: String, message:String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "HI", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil);))
self.present(alert,animated: true, completion:nil)
}
}
The error you are most probably getting is Invalid redeclaration of 'viewDidAppear' means you are trying to add viewDidAppear method twice in your ViewController. So remove the below one method form your code and call createAlert inside the already exist viewDidAppear one.
Your second mistake is you forgot to add } for UIAlertActionHandler and there is no need to call dismiss on alert action it will automatically dismiss the alert.
You need to also change your selector syntax to Swift3 one and also you forgot to add handleReceivedDataWithNotification with your code.
Now with Swift use Swift native dictionary type instead of NSDictionary, so change your controller with below one to get your desired output.
class ViewController: UIViewController, MCBrowserViewControllerDelegate {
#IBOutlet weak var input: UITextField!
#IBOutlet weak var output: UILabel!
var currentPlayer:String!
var appDelegate:AppDelegate!
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.MPCHandler.setupPeerWithDisplayName(UIDevice.current.name)
appDelegate.MPCHandler.setupSession()
appDelegate.MPCHandler.advertiseSelf(true)
NotificationCenter.default.addObserver(self, selector: #selector(peerChangedStateWithNotification(_:)), name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleReceivedDataWithNotification(_:)), name: NSNotification.Name(rawValue: "MPC_DidReceiveDataNotification"), object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func connect(_ sender: Any) {
if appDelegate.MPCHandler.session != nil{
appDelegate.MPCHandler.setupBrowser()
appDelegate.MPCHandler.browser.delegate = self
self.present(appDelegate.MPCHandler.browser, animated: true, completion: nil)
}
}
#IBAction func action(_ sender: Any) {
output.text = input.text
UserDefaults.standard.set(input.text, forKey: "MyName")
input.text = ""
}
func peerChangedStateWithNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
let state = userInfo["state"] as! Int
if state != MCSessionState.connecting.rawValue{
self.navigationItem.title = "Connected"
}
}
func handleReceivedDataWithNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
print(userInfo)
}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
if let x = UserDefaults.standard.string(forKey: "myName") {
output.text = x
}
else {
output.text = "Default Name" //Set here default Name
}
self.createAlert(title: "HI", message: "ARE YOU READY")
}
func createAlert (title: String, message:String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: output.text, style: UIAlertActionStyle.default, handler: { (action) in
}))
self.present(alert,animated: true, completion:nil)
}
}
import UIKit
import MultipeerConnectivity
class ViewController: UIViewController, MCBrowserViewControllerDelegate {
#IBOutlet weak var input: UITextField!
#IBOutlet weak var output: UILabel!
#IBAction func dick(_ sender: Any) {
output.text = input.text
UserDefaults.standard.set(input.text, forKey: "MyName")
input.text = ""
}
var currentPlayer:String!
var appDelegate:AppDelegate!
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.MPCHandler.setupPeerWithDisplayName(UIDevice.current.name)
appDelegate.MPCHandler.setupSession()
appDelegate.MPCHandler.advertiseSelf(true)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.peerChangedStateWithNotification(_:)), name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.handleReceivedDataWithNotification(_:)), name: NSNotification.Name(rawValue: "MPC_DidReceiveDataNotification"), object: nil)
}
#IBAction func connect(_ sender: Any) {
if appDelegate.MPCHandler.session != nil{
appDelegate.MPCHandler.setupBrowser()
appDelegate.MPCHandler.browser.delegate = self
self.present(appDelegate.MPCHandler.browser, animated: true, completion: nil)
}
}
#IBAction func action(_ sender: Any) {
output.text = input.text
UserDefaults.standard.set(input.text, forKey: "MyName")
input.text = ""
}
func peerChangedStateWithNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
let state = userInfo["state"] as! Int
if state != MCSessionState.connecting.rawValue{
self.navigationItem.title = "Connected"
}
}
func handleReceivedDataWithNotification(_ notification: Notification) {
let userInfo = notification.userInfo!
print(userInfo)
}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
appDelegate.MPCHandler.browser.dismiss(animated: true, completion: nil)
}
*func viewdidloadOverride; func viewDidAppear*(_ animated: Bool) {
if let x = UserDefaults.standard.string(forKey: "myName") {
output.text = x
}
else {
output.text = "x" //Set here default Name
}
self.createAlert(title: "HI", message: "ARE YOU READY")
}
func createAlert (title: String, message:String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: output.text, style: UIAlertActionStyle.default, handler: { (action) in
}))
self.present(alert,animated: true, completion:nil)
}
}

Xcode 8 - swift 3: Creating an image format with an unknown type is an error

I get an error when selecting an image with UIImagePicker:
[Generic] Creating an image format with an unknown type is an error
I'm using Xcode 8.1 and Swift 3.
I've already searched all around the web but nothing seems to solve my problem, please help!
Here it's my code:
class TabBarController: UITabBarController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var isSelected: Bool = false
var imgPicker: UIImagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
//imgPicker = UIImagePickerController()
imgPicker.delegate = self
imgPicker.allowsEditing = false
imgPicker.sourceType = .photoLibrary
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imgPicker.dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.performSegue(withIdentifier: "toPostPicture", sender: image)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func askImagePickerSource(sender: UIViewController) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in
self.imgPicker.sourceType = .camera
self.imgPicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .camera)!
sender.present(self.imgPicker, animated: true, completion: nil)
})
let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in
self.imgPicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
sender.present(self.imgPicker, animated: true, completion: nil)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (UIAlertAction) in
sender.dismiss(animated: true, completion: nil)
}
alert.addAction(cameraAction)
alert.addAction(photoLibraryAction)
alert.addAction(cancelAction)
sender.present(alert, animated: true, completion: nil)
} else {
self.imgPicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
sender.present(self.imgPicker, animated: true, completion: nil)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toPostPicture" {
if let postPictureVC = segue.destination as? PostPictureVC {
if let image = sender as? UIImage {
postPictureVC.image = image
}
}
}
}
}
I faced the same issue by not adding delegate as 'self' for the UIImagePickerController. After adding it I was able to get the selected image from gallery. But even after adding delegate as self and able to access the image (Display on an ImageView), I was still getting the same error. After a further research on SO I got to know that this is just a bug and doesn't affect the app in any way.
See also "Creating an image format with an unknown type is an error Objective-C Xcode 8"
Can you post the .debugDescription of the info parameter in your picker delegate?
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
print(info.debugDescription)
...
}