I cant figure out what's the problem here.
I have 6 images and when i click on them it popsup a image picker. If i choose a photo with a sequence, like 1,2,3,4,5,6... it works. But when i choose the first photo that's not the first one (array[0]), i get an error:
`$"Array index out of range"
Here is my code:
class SecondViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagemEscolhida = -1
#IBOutlet var firstImageView: UIImageView!
#IBOutlet var secondImageView: UIImageView!
#IBOutlet var thirdImageView: UIImageView!
#IBOutlet var fourthImageView: UIImageView!
#IBOutlet var fifthImageView: UIImageView!
#IBOutlet var sixthImageView: UIImageView!
#IBAction func firstImageButton(sender: AnyObject) {
imagemEscolhida = 1
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func secondImageButton(sender: AnyObject) {
imagemEscolhida = 2
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func thirdImageButton(sender: AnyObject) {
imagemEscolhida = 3
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func fourthImageButton(sender: AnyObject) {
imagemEscolhida = 4
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func fifthImageButton(sender: AnyObject) {
imagemEscolhida = 5
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func sixthImageButton(sender: AnyObject) {
imagemEscolhida = 6
abreBibliotecaFotos(imagemEscolhida)
}
func abreBibliotecaFotos (img: Int )
{
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
let imagePicker = UIImagePickerController()
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
firstImageView.contentMode = .ScaleAspectFit
restaurante.imagem.insert(pickedImage, atIndex: imagemEscolhida-1)
switch imagemEscolhida
{
case 1:
firstImageView.image = restaurante.imagem[0]
case 2:
secondImageView.image = restaurante.imagem[1]
case 3:
thirdImageView.image = restaurante.imagem[2]
case 4:
fourthImageView.image = restaurante.imagem[3]
case 5:
fifthImageView.image = restaurante.imagem[4]
case 6:
sixthImageView.image = restaurante.imagem[5]
default:
println("Something else")
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
}
You should initialize the array before you use it in the correct size. I would like to refer to my answer to a really similar question.
So initialize it from 0 to 5 at definition then your code should work.
It looks like the restaurante.imagem array is empty and your code crashes because you try to insert something at index which is higher than the maximum index of the array - which is 0.
The line to blame is:
restaurante.imagem.insert(pickedImage, atIndex: imagemEscolhida-1)
Related
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
}
I am developing an App that will ask for 5 images, assign them to the proper UIImageViewer for preview purposes, and then I would like to hit upload and all 5 images go to a team drive. At this point all of it works except the code snippet I have is only able to upload images if they are in the App's Documents Directory. I would like to reference back to the 5 previously chosen images and upload them to a team drive but I do not know how to go about that.
Each button has been assigned a tag number, in which will equal their designated UIImageViewer. I am trying to reference the other previously chosen images but an error says in the 'UploadAction' button "Cannot convert value of type 'UIImage' to expected argument type 'String'". Here is my code, any help would be greatly appreciated!! (This is in Swift in Xcode, I could not find any examples using swift to upload pictures using a phone camera or photo gallery)
import UIKit
import GoogleSignIn
import GoogleAPIClientForREST
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, GIDSignInUIDelegate, UIPickerViewDelegate, UITextFieldDelegate{
// func numberOfComponents(in pickerView: UIPickerView) -> Int {
//
// }
// func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//
// }
#IBOutlet weak var imageView1: UIImageView!
#IBOutlet weak var imageView2: UIImageView!
#IBOutlet weak var imageView3: UIImageView!
#IBOutlet weak var imageView4: UIImageView!
#IBOutlet weak var imageView5: UIImageView!
#IBOutlet weak var resultsLabel: UILabel!
var imagePicker = UIImagePickerController()
var imagePicked = 0
var cameraPicker = UIImagePickerController()
var cameraPicked = 0
fileprivate let service = GTLRDriveService()
private var drive: ATGoogleDrive?
override func viewDidLoad() {
super.viewDidLoad()
cameraPicker.delegate = self
cameraPicker.sourceType = .camera
cameraPicker.allowsEditing = false; imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false;
GIDSignIn.sharedInstance().uiDelegate = self;
self.view.backgroundColor = UIColor.lightGray;
setupGoogleSignIn()
drive = ATGoogleDrive(service)
}
#IBAction func openCamera(_ sender: UIButton){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
cameraPicked = sender.tag
present(cameraPicker, animated: true)
}
}
#IBAction func chooseImage1(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.savedPhotosAlbum){
imagePicked = sender.tag
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
let cameraImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
if imagePicked == 1 {
imageView1.image = pickedImage
} else if imagePicked == 2 {
imageView2.image = pickedImage
} else if imagePicked == 3 {
imageView3.image = pickedImage
} else if imagePicked == 4 {
imageView4.image = pickedImage
} else if imagePicked == 5 {
imageView5.image = pickedImage
} else if cameraPicked == 6 {
imageView1.image = cameraImage
} else if cameraPicked == 7 {
imageView2.image = cameraImage
} else if cameraPicked == 8 {
imageView3.image = cameraImage
} else if cameraPicked == 9 {
imageView4.image = cameraImage
} else if cameraPicked == 10 {
imageView5.image = cameraImage
}
dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true)
}
private func setupGoogleSignIn() {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().scopes = [kGTLRAuthScopeDriveFile]
GIDSignIn.sharedInstance().signInSilently()
}
// MARK: - Actions
**#IBAction func uploadAction(_ sender: Any) {
if let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let uploadem = imageView1.image
drive?.uploadFile("agostini_tech_demo", filePath: uploadem, MIMEType: "image/png") { (fileID, error) in
print("Upload file ID: \(fileID); Error: \(error?.localizedDescription)")**
}
}
}
#IBAction func listAction(_ sender: Any) {
drive?.listFilesInFolder("agostini_tech_demo") { (files, error) in
guard let fileList = files else {
print("Error listing files: \(error?.localizedDescription)")
return
}
self.resultsLabel.text = fileList.files?.description
}
}
}
// MARK: - GIDSignInDelegate
extension ViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let _ = error {
// service.authorizer = nil
} else {
// service.authorizer = user.authentication.fetcherAuthorizer()
}
}
}
I've checked all of my connections and NONE of them are broken. I've reconnected all of them and checked everything but I keep getting this error. It comes in the first line of the App Delegate and I don't know why. Here's the code.
class DetailsViewController: UIViewController, SFSafariViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
let imagePicker = UIImagePickerController()
#IBOutlet weak var MITImageView: UIImageView!
#IBOutlet weak var StanfordImageView: UIImageView!
#IBOutlet weak var HarvardImageView: UIImageView!
#IBAction func MITSafariViewControllerButton(_ sender: UIButton) {
let url = NSURL(string: MITUrl)!
let svc = SFSafariViewController(url: url as URL)
present(svc, animated: true, completion: nil)
}
#IBAction func StanfordSafariViewControllerButton(_ sender: UIButton) {
let url = NSURL(string: StanfordUrl)!
let svc = SFSafariViewController(url: url as URL)
present(svc, animated: true, completion: nil)
}
#IBAction func HarvardSafariViewControllerButton(_ sender: UIButton) {
let url = NSURL(string: HarvardUrl)!
let svc = SFSafariViewController(url: url as URL)
present(svc, animated: true, completion: nil)
}
#IBAction func imageChangeButton(_ sender: UIButton) {
imagePickerClass().imagePickerControllerMIT(picker: imagePicker)
}
#IBAction func imageChangeButtonStanford(_ sender: UIButton) {
imagePickerClass().imagePickerControllerStanford(picker: imagePicker)
}
#IBAction func imageChangeButtonHarvard(_ sender: UIButton) {
imagePickerClass().imagePickerControllerHarvard(picker: imagePicker)
}
var MITUrl = "http://web.mit.edu"
var StanfordUrl = "http://stanford.edu"
var HarvardUrl = "http://www.harvard.edu"
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
var logos = [#imageLiteral(resourceName: "MIT Logo"), #imageLiteral(resourceName: "Stanford Logo"), #imageLiteral(resourceName: "Harvard Logo")]
var pos1 = Int()
var pos2 = Int()
var pos3 = Int()
pos1 = 0
pos2 = 1
pos3 = 2
self.MITImageView.image = logos[pos1]
self.StanfordImageView.image = logos[pos2]
self.HarvardImageView.image = logos[pos3]
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class imagePickerClass : DetailsViewController {
var pos1 = Int()
var pos2 = Int()
var pos3 = Int()
var MITImage = Int()
var StanfordImage = Int()
var HarvardImage = Int()
init (){
pos1 = 0
pos2 = 1
pos3 = 2
MITImage = 3
StanfordImage = 3
HarvardImage = 3
let code = NSCoder()
super.init(coder: code)!
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func imagePickerControllerMIT(picker: UIImagePickerController) {
self.imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
weak var weakSelf = self
weakSelf?.present((weakSelf?.imagePicker)!, animated: true, completion: nil)
self.imagePicker.dismiss(animated: true, completion: {
let imageSelected = [UIImagePickerControllerOriginalImage] as! UIImage
var logos = [#imageLiteral(resourceName: "MIT Logo"), #imageLiteral(resourceName: "Stanford Logo"), #imageLiteral(resourceName: "Harvard Logo"), imageSelected]
self.MITImageView.image = logos[self.MITImage]
})
}
func imagePickerControllerStanford(picker: UIImagePickerController) {
imagePicker.dismiss(animated: true, completion: {
self.imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
weak var weakSelf = self
weakSelf?.present((weakSelf?.imagePicker)!, animated: true, completion: {
let imageSelected = [UIImagePickerControllerOriginalImage] as! UIImage
var logos = [#imageLiteral(resourceName: "MIT Logo"), #imageLiteral(resourceName: "Stanford Logo"), #imageLiteral(resourceName: "Harvard Logo"), imageSelected]
self.MITImageView.image = logos[self.StanfordImage]
})
})
}
func imagePickerControllerHarvard(picker: UIImagePickerController) {
imagePicker.dismiss(animated: true, completion: {
self.imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
weak var weakSelf = self
weakSelf?.present((weakSelf?.imagePicker)!, animated: true, completion: {
let imageSelected = [UIImagePickerControllerOriginalImage] as! UIImage
var logos = [#imageLiteral(resourceName: "MIT Logo"), #imageLiteral(resourceName: "Stanford Logo"), #imageLiteral(resourceName: "Harvard Logo"), imageSelected]
self.MITImageView.image = logos[self.HarvardImage]
})
})
}
}
Heres the error
class AppDelegate: UIResponder, UIApplicationDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
If you could help me figure this out that would be great.
First want to say that I am using Xcode 7.0 and IOS 9.0. And I have also got a same problem in objective-c. I found the cause of exception simply debugging my code (Basically which line is responsible for it). And I am going to share with you. Though your question is swift related, I am just trying to help about the signal 1: SIGABRT. It's may help you.
1. First set a debug pointer of your code at any line. click show the break point navigator icon.
2. click create a break point icon.
3. click Add Exception BreakPoint.
4. Right click on the All Exception and click Edit BreakPoint.
5. select objective-c as an option of 'Exception'.
And run your application. It will take you to the corresponding line for which you get SIGABRT.
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)
}
}
}
Whenever I try to open a different view controller with a show segue it crashes with this error Swift: Thread 1 signal SIGABRT in class AppDelegate: UIResponder, UIApplicationDelegate, I don't know why.
Here's the code of the View Controller that I try to open:
import UIKit
import CoreData
class AddEditVC: UIViewController, NSFetchedResultsControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var item : Item? = nil
#IBOutlet weak var itemName: UITextField!
#IBOutlet weak var imageHolder: UIImageView!
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
if item != nil {
itemName.text = item?.name
imageHolder.image = UIImage(data: (item?.image)!)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addImage(sender: AnyObject) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
pickerController.allowsEditing = true
self.presentViewController(pickerController, animated: true, completion: nil)
}
#IBAction func addImageFromCamera(sender: AnyObject) {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = UIImagePickerControllerSourceType.Camera
pickerController.allowsEditing = true
self.presentViewController(pickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
self.imageHolder.image = image
}
#IBAction func saveTapped(sender: AnyObject) {
if item != nil {
editItem()
} else {
createNewItem()
}
}
func createNewItem() {
let entityDescription = NSEntityDescription.entityForName("Item", inManagedObjectContext: moc)
let item = Item(entity: entityDescription!, insertIntoManagedObjectContext: moc)
item.name = itemName.text
item.image = UIImagePNGRepresentation(imageHolder.image!)
do {
try moc.save()
} catch {
return
}
}
func editItem () {
item?.name = itemName.text
item!.image = UIImagePNGRepresentation(imageHolder.image!)
do {
try moc.save()
} catch {
return
}
}
This error is usually appears when some of #IBOutlet or #IBAction is not assigned in the MainStoryboard.
Please check small circles before them. They should be grayed
It's either what Andriy is saying, or you executed a PerformSegueWithIdentifier(name, nil) with the wrong identifier. Best to add a screenshot of your storyboard & original controller as well to give a definite answer.
Good luck!