Swift Error: EXE_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) - xcode

I'm trying to make this posting app similar to instagram but I am getting stuck on a issue once i press my compose button. This button is suppose to post the image but instead its crashing. I'm having an error after I try to upload a caption\image with my app here:
let imageData = UIImagePNGRepresentation(imageToBeUploaded!)!
It is giving me this error:EXE_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Please help!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var previewImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
captionTextView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addImageTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary)!
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.previewImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
captionTextView.resignFirstResponder()
return true;
}
#IBAction func composeTapped(sender: AnyObject) {
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
let localDate = dateFormatter.stringFromDate(date)
let imageToBeUploaded = self.previewImage.image
let imageData = UIImagePNGRepresentation(imageToBeUploaded!)!
let file: PFFile = PFFile(data: imageData)!
let fileCaption: String = self.captionTextView.text
let photoToUpload = PFObject(className: "Posts")
photoToUpload["Image"] = file
photoToUpload["Caption"] = fileCaption
photoToUpload["addedBy"] = PFUser.currentUser()?.username
photoToUpload["data"] = localDate
//Get bytes size of image
/* var imageSize = Float(imageData!.length)
//Transform into Megabytes
imageSize = imageSize/(1024*1024)
print("Image size is \(imageSize)Mb")
*/
do{
try photoToUpload.save()
} catch _ {
}
print("Successfully Posted.")
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("postController")
self.presentViewController(vc! as UIViewController, animated: true, completion: nil)
}

It seems that you are unwraping an optional value without actualy checking if it is nil.
Probably the issue is from let file: PFFile = PFFile(data: imageData)!. You must check for nil before you unwrap a variable.

Related

GeoTag Images from image picker swift 3

I want to get geotag location from image which is selected from image picker. I am using this code
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary
{
if let currentLat = pickedLat as CLLocationDegrees?
{
self.latitude = pickedLat!
self.longitude = pickedLong!
}
else
{
var library = ALAssetsLibrary()
library.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { (group, stop) -> Void in
if (group != nil) {
println("Group is not nil")
println(group.valueForProperty(ALAssetsGroupPropertyName))
group.enumerateAssetsUsingBlock { (asset, index, stop) in
if asset != nil
{
if let location: CLLocation = asset.valueForProperty(ALAssetPropertyLocation) as CLLocation!
{ let lat = location.coordinate.latitude
let long = location.coordinate.longitude
self.latitude = lat
self.longitude = lat
println(lat)
println(long)
}
}
}
} else
{
println("The group is empty!")
}
})
{ (error) -> Void in
println("problem loading albums: \(error)")
}
}
}
i want to know to covert this code in swift 3 .I am new in coding with swift 3 .It will be very helpful
After hours of searching i got my ans
import UIKit
import Photos
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var logi: UILabel!
#IBOutlet weak var lati: UILabel!
var lat = String()
var log = String()
var location = String()
var timeTaken = "Not Known"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func imagegeo(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var chosenImage:UIImage?
if let URL = info[UIImagePickerControllerReferenceURL] as? URL {
print("We got the URL as \(URL)")
let opts = PHFetchOptions()
opts.fetchLimit = 1
let assets = PHAsset.fetchAssets(withALAssetURLs: [URL], options: opts)
print(assets)
for assetIndex in 0..<assets.count {
let asset = assets[assetIndex]
location = String(describing: asset.location)
log = String(describing: asset.location?.coordinate.longitude)
lat = String(describing: asset.location?.coordinate.latitude)
timeTaken = (asset.creationDate?.description)!
print(log)
print(location)
print(lat)
}
}
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
chosenImage = editedImage
} else if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
chosenImage = selectedImage
}
dismiss(animated: true) {
DispatchQueue.main.async {
self.imageView.image = chosenImage
self.timeLabel.text = self.timeTaken
self.locationLabel.text = self.location
self.lati.text = self.lat
self.logi.text = self.log
}
}
}
}

Fatal error editing core data objects

I am newbie to programming. With CoreData, I am trying to create the function to edit the data in input text field to edit the data to be saved to core data. I am having fatal error:
unexpectedly found nil while unwrapping an Optional value
#IBAction func update(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Coursework")
do {
let results = try manageContext.executeFetchRequest(fetchRequest)
let attribute = results[0] as! NSManagedObject
detailItem?.value = modulename.text
attribute.setValue(courseworkname.text, forkey: "courseworkname")
attribute.setValue(dueDateLabel.text, forkey: "duedate")
attribute.setValue(level.text, forkey: "level")
attribute.setValue(mark.text, forkey: "mark")
attribute.setValue(modulename.text, forkey: "modulename")
attribute.setValue(notes.text, forkey: "notes")
attribute.setValue(progressbar.text, forkey: "progressbar")
attribute.setValue(reminder.text, forkey: "reminder")
attribute.setValue(value.text, forkey: "value")
try manageContext.save()
}catch let error as NSError {
}
}
Full code:
#IBOutlet weak var detailDescriptionLabel: UILabel!
#IBOutlet weak var dueDateLabel: UITextField!
#IBOutlet weak var value: UITextField!
#IBOutlet weak var courseworkname: UITextField!
#IBOutlet weak var modulename: UITextField!
#IBOutlet weak var level: UITextField!
#IBOutlet weak var mark: UITextField!
#IBOutlet weak var reminder: UITextField!
#IBOutlet weak var notes: UITextField!
#IBAction func edit(sender: AnyObject) {
modulename.userInteractionEnabled = true
modulename.enabled = true
dueDateLabel.userInteractionEnabled = true
value.userInteractionEnabled = true
modulename.userInteractionEnabled = true
level.userInteractionEnabled = true
mark.userInteractionEnabled = true
reminder.userInteractionEnabled = true
notes.userInteractionEnabled = true
//Interaction
value.enabled = true
dueDateLabel.enabled = true
courseworkname.enabled = true
modulename.enabled = true
level.enabled = true
mark.enabled = true
reminder.enabled = true
notes.enabled = true
}
#IBAction func update(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Coursework")
do {
let results = try manageContext.executeFetchRequest(fetchRequest)
let attribute = results[0] as! NSManagedObject
detailItem?.value = modulename.text
attribute.setValue(courseworkname.text, forKey: "courseworkname")
attribute.setValue(dueDateLabel.text, forKey: "duedate")
attribute.setValue(level.text, forKey: "level")
attribute.setValue(mark.text, forKey: "mark")
attribute.setValue(modulename.text, forKey: "modulename")
attribute.setValue(notes.text, forKey: "notes")
attribute.setValue(progressbar.text, forKey: "progressbar")
attribute.setValue(reminder.text, forKey: "reminder")
attribute.setValue(value.text, forKey: "value")
try manageContext.save()
}catch let error as NSError{
}
}
var detailItem: Coursework?
var detailItem2: Task?
{
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.courseworkname
}
if let label = self.dueDateLabel {
label.text = detail.duedate
}
if let label = self.value {
label.text = detail.value
}
if let label = self.courseworkname {
label.text = detail.courseworkname
}
if let label = self.modulename {
label.text = detail.modulename
}
if let label = self.level {
label.text = detail.level
}
if let label = self.mark {
label.text = detail.mark
}
if let label = self.reminder{
label.text = detail.reminder
}
if let label = self.notes{
label.text = detail.notes
}
}
Is it a new attribute? You have to uninstall and reinstall the app when you're changing your CoreData models.
Also just saw that you don't have an IBOutlet defined for progressbar, if you link it it should work.

Resize image from internet

My app retrieves an image from URL, but I need to change the image size before it appears on the user interface in my tableview.
Here is my tableViewController code:
import UIKit
import Firebase
import Alamofire
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postField: MaterialTextField!
#IBOutlet weak var imageSelectorImage: UIImageView!
var posts = [Post]()
var imageSelected = false
var imagePicker: UIImagePickerController!
static var imageCache = NSCache()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
postField.delegate = self
//tableView.estimatedRowHeight = 400
//tableView.rowHeight = UITableViewAutomaticDimension
imagePicker = UIImagePickerController()
imagePicker.delegate = self
DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").observeEventType(.Value, withBlock: { snapshot in
self.posts = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.posts.insert(post, atIndex: 0)
}
}
}
self.tableView.reloadData()
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 167)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 167)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.1
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
print(post.postDescription)
if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {
cell.request?.cancel()
var img: UIImage?
if let url = post.imageUrl {
img = FeedViewController.imageCache.objectForKey(url) as? UIImage
}
cell.configureCell(post, img: img)
return cell
} else {
return PostCell()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageSelectorImage.image = image
imageSelected = true
}
#IBAction func selectImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func makePost(sender: AnyObject) {
//TODO: Add loading spinner while data is being processed
if let txt = postField.text where txt != "" {
if let img = imageSelectorImage.image where imageSelected == true {
let urlStr = URL_IMGSHACK
let url = NSURL(string: urlStr)!
//FIXME: Add error handling
let imgData = UIImageJPEGRepresentation(img, 0.2)!
let keyData = API_KEY_IMG.dataUsingEncoding(NSUTF8StringEncoding)!
let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!
Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imgData, name: "fileupload", fileName: "image",
mimeType: "image/jpg")
multipartFormData.appendBodyPart(data: keyData, name: "key")
multipartFormData.appendBodyPart(data: keyJSON, name: "format")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { response in
if let info = response.result.value as? Dictionary<String, AnyObject> {
if let links = info["links"] as? Dictionary<String, AnyObject>{
if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
self.postToFirebase(imgLink)
}
}
}
})
case .Failure(let error):
print(error)
}
}
} else {
self.postToFirebase(nil)
}
}
}
func postToFirebase(imgUrl: String?) {
var post: Dictionary<String, AnyObject> = [
"timestamp": NSNumber(longLong: currentTimeMillis()),
"description": postField.text!,
"likes": 0
]
if imgUrl != nil {
post["imageUrl"] = imgUrl!
}
let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
firebasePost.setValue(post)
postField.text = ""
imageSelectorImage.image = UIImage(named: "camera")
imageSelected = false
tableView.reloadData()
postField.resignFirstResponder()
}
func currentTimeMillis() ->Int64 {
let nowDouble = NSDate().timeIntervalSince1970
return Int64(nowDouble * 1000)
}
}
and here is my custom cell:
class PostCell: UITableViewCell {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var showcaseImage: UIImageView!
#IBOutlet weak var descriptionText: UILabel!
#IBOutlet weak var likesLabel: UILabel!
#IBOutlet weak var likeImage: UIImageView!
var post: Post!
var request: Request?
var likeRef: Firebase!
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: "likeTapped:")
tap.numberOfTapsRequired = 1
likeImage.addGestureRecognizer(tap)
likeImage.userInteractionEnabled = true
}
override func drawRect(rect: CGRect) {
profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2
profileImage.backgroundColor = UIColor.clearColor()
profileImage.layer.borderWidth = 2
profileImage.layer.borderColor = UIColor.whiteColor().CGColor
self.profileImage.clipsToBounds = true
self.showcaseImage.clipsToBounds = true
}
func configureCell(post: Post, img: UIImage?){
self.post = post
likeRef = DataService.ds.REF_USERS_CURRENT.childByAppendingPath("likes").childByAppendingPath(post.postKey)
self.descriptionText.text = post.postDescription
self.likesLabel.text = "\(post.likes)"
if post.imageUrl != nil {
if img != nil {
self.showcaseImage.image = img
} else {
request = Alamofire.request(.GET, post.imageUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request, response, data, err in
if err == nil {
let img = UIImage(data: data!)!
self.showcaseImage.image = img
FeedViewController.imageCache.setObject(img, forKey: self.post.imageUrl!)
} else {
print(err.debugDescription)
}
})
}
} else {
self.showcaseImage.hidden = true
}
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
//This mean we have not liked this specific post
self.likeImage.image = UIImage(named: "heart-empty")
} else {
self.likeImage.image = UIImage(named: "heart-full")
}
})
}
func likeTapped(sender: UITapGestureRecognizer) {
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
self.likeImage.image = UIImage(named: "heart-full")
self.post.adjustLikes(true)
self.likeRef.setValue(true)
} else {
self.likeImage.image = UIImage(named: "heart-empty")
self.post.adjustLikes(false)
self.likeRef.removeValue()
}
})
}
}
Here is an example showing what I want to achieve:
this when user post the portrait image
this when user post the landscape image
In summary, I want the image width to fit the width of the device screen, and the height of the uiimage to be dynamic, regardless of the image orientation (landscape or portrait).
Try this part, where 300x600 is needed size of your image to save.
let image = UIImage(data: data!)
UIGraphicsBeginImageContext(CGSizeMake(300, 600))
image?.drawInRect(CGRectMake(0, 0, 300, 600))
let smallImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

need help about resize image swift 2

My app retrieves image from URL, but I need to change the image size before it appears on the user interface in my tableview.
this is my code in my tableViewController:
import UIKit
import Firebase
import Alamofire
class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postField: MaterialTextField!
#IBOutlet weak var imageSelectorImage: UIImageView!
var posts = [Post]()
var imageSelected = false
var imagePicker: UIImagePickerController!
static var imageCache = NSCache()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
postField.delegate = self
//tableView.estimatedRowHeight = 400
//tableView.rowHeight = UITableViewAutomaticDimension
imagePicker = UIImagePickerController()
imagePicker.delegate = self
DataService.ds.REF_POSTS.queryOrderedByChild("timestamp").observeEventType(.Value, withBlock: { snapshot in
self.posts = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.posts.insert(post, atIndex: 0)
}
}
}
self.tableView.reloadData()
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 167)
}
func textFieldDidEndEditing(textField: UITextField) {
animateViewMoving(false, moveValue: 167)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
let movementDuration:NSTimeInterval = 0.1
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
print(post.postDescription)
if let cell = tableView.dequeueReusableCellWithIdentifier("PostCell") as? PostCell {
cell.request?.cancel()
var img: UIImage?
if let url = post.imageUrl {
img = FeedViewController.imageCache.objectForKey(url) as? UIImage
}
cell.configureCell(post, img: img)
return cell
} else {
return PostCell()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
imageSelectorImage.image = image
imageSelected = true
}
#IBAction func selectImage(sender: UITapGestureRecognizer) {
presentViewController(imagePicker, animated: true, completion: nil)
}
#IBAction func makePost(sender: AnyObject) {
//TODO: Add loading spinner while data is being processed
if let txt = postField.text where txt != "" {
if let img = imageSelectorImage.image where imageSelected == true {
let urlStr = URL_IMGSHACK
let url = NSURL(string: urlStr)!
//FIXME: Add error handling
let imgData = UIImageJPEGRepresentation(img, 0.2)!
let keyData = API_KEY_IMG.dataUsingEncoding(NSUTF8StringEncoding)!
let keyJSON = "json".dataUsingEncoding(NSUTF8StringEncoding)!
Alamofire.upload(.POST, url, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imgData, name: "fileupload", fileName: "image",
mimeType: "image/jpg")
multipartFormData.appendBodyPart(data: keyData, name: "key")
multipartFormData.appendBodyPart(data: keyJSON, name: "format")
}) { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { response in
if let info = response.result.value as? Dictionary<String, AnyObject> {
if let links = info["links"] as? Dictionary<String, AnyObject>{
if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
self.postToFirebase(imgLink)
}
}
}
})
case .Failure(let error):
print(error)
}
}
} else {
self.postToFirebase(nil)
}
}
}
func postToFirebase(imgUrl: String?) {
var post: Dictionary<String, AnyObject> = [
"timestamp": NSNumber(longLong: currentTimeMillis()),
"description": postField.text!,
"likes": 0
]
if imgUrl != nil {
post["imageUrl"] = imgUrl!
}
let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
firebasePost.setValue(post)
postField.text = ""
imageSelectorImage.image = UIImage(named: "camera")
imageSelected = false
tableView.reloadData()
postField.resignFirstResponder()
}
func currentTimeMillis() ->Int64 {
let nowDouble = NSDate().timeIntervalSince1970
return Int64(nowDouble * 1000)
}
}
and here my custom cell:
class PostCell: UITableViewCell {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var showcaseImage: UIImageView!
#IBOutlet weak var descriptionText: UILabel!
#IBOutlet weak var likesLabel: UILabel!
#IBOutlet weak var likeImage: UIImageView!
var post: Post!
var request: Request?
var likeRef: Firebase!
override func awakeFromNib() {
super.awakeFromNib()
let tap = UITapGestureRecognizer(target: self, action: "likeTapped:")
tap.numberOfTapsRequired = 1
likeImage.addGestureRecognizer(tap)
likeImage.userInteractionEnabled = true
}
override func drawRect(rect: CGRect) {
profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2
profileImage.backgroundColor = UIColor.clearColor()
profileImage.layer.borderWidth = 2
profileImage.layer.borderColor = UIColor.whiteColor().CGColor
self.profileImage.clipsToBounds = true
self.showcaseImage.clipsToBounds = true
}
func configureCell(post: Post, img: UIImage?){
self.post = post
likeRef = DataService.ds.REF_USERS_CURRENT.childByAppendingPath("likes").childByAppendingPath(post.postKey)
self.descriptionText.text = post.postDescription
self.likesLabel.text = "\(post.likes)"
if post.imageUrl != nil {
if img != nil {
self.showcaseImage.image = img
} else {
request = Alamofire.request(.GET, post.imageUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request, response, data, err in
if err == nil {
let img = UIImage(data: data!)!
self.showcaseImage.image = img
FeedViewController.imageCache.setObject(img, forKey: self.post.imageUrl!)
} else {
print(err.debugDescription)
}
})
}
} else {
self.showcaseImage.hidden = true
}
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
//This mean we have not liked this specific post
self.likeImage.image = UIImage(named: "heart-empty")
} else {
self.likeImage.image = UIImage(named: "heart-full")
}
})
}
func likeTapped(sender: UITapGestureRecognizer) {
likeRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let doesNotExist = snapshot.value as?
NSNull {
self.likeImage.image = UIImage(named: "heart-full")
self.post.adjustLikes(true)
self.likeRef.setValue(true)
} else {
self.likeImage.image = UIImage(named: "heart-empty")
self.post.adjustLikes(false)
self.likeRef.removeValue()
}
})
}
}
this example for what i want to achieve:
this when user post the portrait image
this when user post the landscape image
The point is that I want my image width to always fit the width of device screen, and the height of the uiimage will be dynamic.
so when user post any image with any orientation ( landscape or portrait ), the image will fit the width of the screen, the height will be dynamic.
please help me give the detail where to put your method since i am a newbie about this, how to achieve what i want... im so desperated, is already 1 month and im so stuck about this...
You need to add imageview to storyboard from interface builder in Xcode,then you can set its constraints to fit size of the screen,& also add height constraints which you can change later when you retrieve image from url

how do to get an image from one viewController to the next like a global

I have just a camera on my CameraController. I want the picture from my CameraContoller to go to my ComposeViewController inside of the image View in the ComposeViewController. so basically I need it so the the picture taken transfers to the other view controller once taken. There are 2 separate view controllers below in the code.
Code:
import UIKit
import AVFoundation
class CameraController : UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?
#IBOutlet var cameraView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
previewLayer?.frame = cameraView.bounds
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error : NSError?
var input = AVCaptureDeviceInput(device: backCamera, error: &error)
if (error == nil && captureSession?.canAddInput(input) != nil){
captureSession?.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if (captureSession?.canAddOutput(stillImageOutput) != nil){
captureSession?.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer)
captureSession?.startRunning()
}
}
}
#IBOutlet var tempImageView: UIImageView!
func didPressTakePhoto(){
if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
(sampleBuffer, error) in
if sampleBuffer != nil {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
var dataProvider = CGDataProviderCreateWithCFData(imageData)
var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)
var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)
self.tempImageView.image = image
self.tempImageView.hidden = false
}
})
}
}
var didTakePhoto = Bool()
func didPressTakeAnother(){
if didTakePhoto == true{
tempImageView.hidden = true
didTakePhoto = false
}
else{
captureSession?.startRunning()
didTakePhoto = true
didPressTakePhoto()
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
didPressTakeAnother()
}
}
//-----Below is my Next View Controller where i want the image from the above view controller to show up--------------------------------------- --------------------------------------------------------------------------- --------------
class ComposeViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var previewImage: UIImageView!
let tap = UITapGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "GotoProfile")
swipe.direction = UISwipeGestureRecognizerDirection.Right
self.view.addGestureRecognizer(swipe)
tap.numberOfTapsRequired = 2
tap.addTarget(self, action: "GoBack")
view.userInteractionEnabled = true
view.addGestureRecognizer(tap)
captionTextView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func CaptonField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if range.length + range.location > count(captionTextView.text){
return false
}
let NewLength = count(captionTextView.text) + count(string) - range.length
return NewLength <= 35
}
#IBAction func chooseImageFromCamera() {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker,animated: true, completion:nil)
}
func GotoProfile(){
self.performSegueWithIdentifier("NewCameraViewFromComposeSegue", sender: nil)
}
func GoBack(){
self.performSegueWithIdentifier("GoBackFromCamerasegue", sender: nil)
}
#IBAction func addImageTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary)!
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.previewImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
captionTextView.resignFirstResponder()
return true;
}
#IBAction func composeTapped(sender: AnyObject) {
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
let localDate = dateFormatter.stringFromDate(date)
let imageToBeUploaded = self.previewImage.image
let imageData = UIImagePNGRepresentation(imageToBeUploaded)
let file: PFFile = PFFile(data: imageData)
let fileCaption: String = self.captionTextView.text
var photoToUpload = PFObject(className: "Posts")
photoToUpload["Image"] = file
photoToUpload["Caption"] = fileCaption
photoToUpload["addedBy"] = PFUser.currentUser()?.username
photoToUpload["date"] = localDate
photoToUpload.save()
println("Successfully Posted.")
let vc: AnyObject? = self.storyboard?.instantiateViewControllerWithIdentifier("NavigationController")
self.presentViewController(vc as! UIViewController, animated: true, completion: nil)
}
}
Are you using a segue to get from the first to the second ViewController ?
If so you can access the second VC in in your first VC in the prepareForSegue function :
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ComposeVCIdentifier" {
let composeViewController = segue.destinationViewController as! ComposeViewController
composeViewController.someVariable = myPicture
}
}

Resources