need help about resize image swift 2 - uiimageview

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

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
}
}
}
}

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()

How to make collectionView stop blinking

I have a problem with my collection view, which gives me a 'blink' a second after the view gets appeared on the screen.
Could it be the viewDidLoad or the viewDidAppear that causes this?
This is my current Swift code:
class HomeViewController: UIViewController
{
// MARK: IBOutlets
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var currentUserProfileImageButton: UIButton!
#IBOutlet weak var currentUserFullNameButton: UIButton!
// MARK: - UICollectionViewDataSource
private var interests = [Interest]()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if PFUser.currentUser() == nil {
// the user hasn't logged in yet
showLogin()
} else {
// the user logged in, do something else
fetchInterests()
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
center.addObserverForName("NewInterestCreated", object: nil, queue: queue, usingBlock: { (notification) -> Void in
if let newInterest = notification.userInfo?["newInterestObject"] as? Interest {
if !self.interestWasDisplayed(newInterest) {
self.interests.insert(newInterest, atIndex: 0)
self.collectionView.reloadData()
}
}
})
}
}
func interestWasDisplayed(newInterest: Interest) -> Bool {
for interest in interests {
if interest.objectId! == newInterest.objectId! {
return true
}
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if UIScreen.mainScreen().bounds.size.height == 480.0 {
let flowLayout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.itemSize = CGSizeMake(250.0, 300.0)
}
configureUserProfile()
}
func configureUserProfile()
{
// configure image button
currentUserProfileImageButton.contentMode = UIViewContentMode.ScaleAspectFill
currentUserProfileImageButton.layer.cornerRadius = currentUserProfileImageButton.bounds.width / 2
currentUserProfileImageButton.layer.masksToBounds = true
}
private struct Storyboard {
static let CellIdentifier = "Interest Cell"
}
#IBAction func userProfileButtonClicked()
{
PFUser.logOut()
showLogin()
}
// MARK: - Fetch Data From Parse
func fetchInterests()
{
let currentUser = User.currentUser()!
let interestIds = currentUser.interestIds
if interestIds?.count > 0
{
let interestQuery = PFQuery(className: Interest.parseClassName())
interestQuery.orderByDescending("updatedAt")
interestQuery.cachePolicy = PFCachePolicy.NetworkElseCache
interestQuery.whereKey("objectId", containedIn: interestIds)
interestQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let interestObjects = objects as [PFObject]? {
self.interests.removeAll()
for interestObject in interestObjects {
let interest = interestObject as! Interest
self.interests.append(interest)
}
self.collectionView.reloadData()
}
} else {
print("\(error!.localizedDescription)")
}
})
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Show Interest" {
let cell = sender as! InterestCollectionViewCell
let interest = cell.interest
let navigationViewController = segue.destinationViewController as! UINavigationController
let interestViewController = navigationViewController.topViewController as! InterestViewController
interestViewController.interest = interest
} else if segue.identifier == "CreateNewInterest" {
_ = segue.destinationViewController as! NewInterestViewController
} else if segue.identifier == "Show Discover" {
_ = segue.destinationViewController as! DiscoverViewController
}
}
func showLogin()
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let welcomeNavigationVC = storyboard.instantiateViewControllerWithIdentifier("WelcomeNavigationViewController") as! UINavigationController
self.presentViewController(welcomeNavigationVC, animated: true, completion: nil)
}
}
extension HomeViewController : UICollectionViewDataSource{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return interests.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath: indexPath) as! InterestCollectionViewCell
cell.interest = self.interests[indexPath.item]
return cell
}
}
extension HomeViewController : UIScrollViewDelegate{
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing
var offset = targetContentOffset.memory
let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
let roundedIndex = round(index)
offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
targetContentOffset.memory = offset
}
}
extension HomeViewController : PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate{
func presentLoginViewController()
{
let logInController = PFLogInViewController()
let signupController = PFSignUpViewController()
signupController.delegate = self
logInController.delegate = self
logInController.fields = [PFLogInFields.UsernameAndPassword, PFLogInFields.LogInButton, PFLogInFields.SignUpButton]
logInController.signUpController = signupController
presentViewController(logInController, animated: true, completion: nil)
}
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser)
{
logInController.dismissViewControllerAnimated(true, completion: nil)
}
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser)
{
signUpController.dismissViewControllerAnimated(true, completion: nil)
}
}
Thanks guys :)

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
}
}

Terminator found in the middle of a basic block

All went fine until my project won't compile.I see those things on two of my files.
Terminator found in the middle of a basic block!
label %50
LLVM ERROR: Broken function found, compilation aborted!
Terminator found in the middle of a basic block!
label %71
LLVM ERROR: Broken function found, compilation aborted!
And the error the compiler give
Command /Applications/Xcode-beta 2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
I tried solving it, but no success.
Older version of the files compile.
The problem is in the files,but what is the terminator?
Where is the problem?
EDIT
Here is some code, the classes are big
LandscapeViewController
import UIKit
class LandscapeViewController: UIViewController,UIScrollViewDelegate {
// MARK: Properties
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageControl: UIPageControl!
var search: Search!
private var firstTime = true
private var downloadTasks = [NSURLSessionDownloadTask]()
#IBAction func pageChange(sender: UIPageControl){
UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.scrollView.contentOffset = CGPoint(x: self.scrollView.bounds.size.width * CGFloat(sender.currentPage), y: 0)
}, completion: nil )
}
// MARK: Buttons
private func tileButtons(searchResults: [SearchResult]){
var columnsPerPage = 5
var rowsPerPage = 3
var itemWidth: CGFloat = 96
var itemHeight: CGFloat = 88
var marginX: CGFloat = 0
var marginY: CGFloat = 20
let buttonWidth: CGFloat = 82
let buttonHeight: CGFloat = 82
let scrollViewWidth = scrollView.bounds.size.width
switch scrollViewWidth{
case 568:
columnsPerPage = 6
itemWidth = 94
marginX = 2
case 667:
columnsPerPage = 7
itemWidth = 95
itemHeight = 98
marginX = 1
marginY = 29
case 736:
columnsPerPage = 8
rowsPerPage = 4
itemWidth = 92
default:
break
}
let paddingHorz = (itemWidth - buttonWidth)/2
let paddingVert = (itemHeight - buttonHeight)/2
var row = 0
var column = 0
var x = marginX
for (index,searchResult) in searchResults.enumerate(){
let button = UIButton(type: .Custom)
button.setBackgroundImage(UIImage(named: "LandscapeButton"), forState: .Normal)
downloadImageForSearchResult(searchResult, andPlaceOnButton: button)
button.tag = 2000 + index
button.addTarget(self, action: Selector("buttonPressed:"), forControlEvents: .TouchUpInside)
button.backgroundColor = UIColor.whiteColor()
button.frame = CGRect(x: x + paddingHorz, y: marginY + CGFloat(row)*itemHeight + paddingVert, width: buttonWidth, height: buttonHeight)
scrollView.addSubview(button)
++row
if row == rowsPerPage{
row = 0
++column
x += itemWidth
if column == columnsPerPage{
column = 0
x += marginX * 2
}
}
}
let buttonsPerPage = columnsPerPage * rowsPerPage
let numPages = 1 + (searchResults.count - 1) / buttonsPerPage
pageControl.numberOfPages = numPages
pageControl.currentPage = 0
scrollView.contentSize = CGSize(width: CGFloat(numPages) * scrollViewWidth, height: scrollView.bounds.size.height)
}
private func downloadImageForSearchResult(searchResult: SearchResult,andPlaceOnButton button: UIButton){
if let url = NSURL(string: searchResult.artworkURL60){
let session = NSURLSession.sharedSession()
let downloadTask = session.downloadTaskWithURL(url,completionHandler: { [weak button] url, response, error in
if error == nil && url != nil{
if let data = NSData(contentsOfURL: url!){
if let image = UIImage(data: data){
let resizedImage = image.resizedImageWithBounds(CGSize(width: 60, height: 60))
dispatch_async(dispatch_get_main_queue()){
if let button = button{
button.setImage(resizedImage, forState: .Normal)
}
}
}
}
}
})
downloadTasks.append(downloadTask!)
downloadTask?.resume()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail"{
switch search.state{
case .Results(let list):
let destinationViewController = segue.destinationViewController as! DetailViewController
let searchResult = list[sender!.tag - 2000]
destinationViewController.searchResult = searchResult
default:
break
}
}
}
func buttonPressed(sender: UIButton){
performSegueWithIdentifier("ShowDetail", sender: sender)
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
let width = scrollView.bounds.size.width
let currentPage = Int((scrollView.contentOffset.x + width/2) / width)
pageControl.currentPage = currentPage
}
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
pageControl.numberOfPages = 0
scrollView.backgroundColor = UIColor(patternImage: UIImage(named: "LandscapeBackground")!)
view.removeConstraints(view.constraints)
view.translatesAutoresizingMaskIntoConstraints = true
pageControl.removeConstraints(pageControl.constraints)
pageControl.translatesAutoresizingMaskIntoConstraints = true
scrollView.removeConstraints(scrollView.constraints)
scrollView.translatesAutoresizingMaskIntoConstraints = true
// Do any additional setup after loading the view.
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollView.frame = view.bounds
pageControl.frame = CGRect(x: 0, y: view.frame.size.height - pageControl.frame.size.height, width: view.frame.size.width, height: pageControl.frame.size.height)
if firstTime{
firstTime = false
switch search.state{
case .NotSearchedYet:
break
case .Loading:
showSpinner()
case .NoResults:
showNothingFoundLabel()
case.Results(let list):
tileButtons(list)
}
}
}
private func showNothingFoundLabel() {
let label = UILabel(frame: CGRect.zeroRect)
label.text = "Nothing Found"
label.backgroundColor = UIColor.clearColor()
label.textColor = UIColor.whiteColor()
label.sizeToFit()
var rect = label.frame
rect.size.width = ceil(rect.size.width/2) * 2
rect.size.height = ceil(rect.size.height/2) * 2
label.frame = rect
label.center = CGPoint(x: CGRectGetMidX(scrollView.bounds), y: CGRectGetMidY(scrollView.bounds))
view.addSubview(label)
}
private func showSpinner(){
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
spinner.center = CGPoint(x: CGRectGetMidX(scrollView.bounds) + 0.5, y: CGRectGetMidY(scrollView.bounds) + 0.5)
spinner.tag = 1000
view.addSubview(spinner)
spinner.startAnimating()
}
func searchResultsRecived(){
hideSpinner()
switch search.state {
case .NotSearchedYet, .Loading:
break
case .NoResults:
showNothingFoundLabel()
case .Results(let list):
tileButtons(list)
}
}
private func hideSpinner(){
view.viewWithTag(1000)?.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
print("deinit \(self)")
for task in downloadTasks{
task.cancel()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
SearchViewController
import UIKit
class SearchViewController: UIViewController,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate {
private struct TableViewCellIdentifier {
static let searchResultCell = "SearchResultCell"
static let nothingFoundCell = "NothingFoundCell"
static let loadingCell = "LoadingCell"
}
// MARK: LandscapeViewController
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
switch newCollection.verticalSizeClass{
case .Compact:
showLandscapeViewWithCoordinator(coordinator)
case .Regular,.Unspecified:
hideLandscapeViewWithCoordinator(coordinator)
}
}
private func showLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator){
precondition(landscapeViewController == nil)
landscapeViewController = storyboard?.instantiateViewControllerWithIdentifier("LandscapeViewController") as? LandscapeViewController
if let controller = landscapeViewController{
controller.search = search
controller.view.frame = view.frame
controller.view.alpha = 0
view.addSubview(controller.view)
addChildViewController(controller)
coordinator.animateAlongsideTransition({ _ in
if self.presentedViewController != nil{
self.dismissViewControllerAnimated(true, completion: nil)
}
self.searchBar.resignFirstResponder()
controller.view.alpha = 1
}, completion: { _ in
controller.didMoveToParentViewController(self)
})
}
}
private func hideLandscapeViewWithCoordinator(coordinator: UIViewControllerTransitionCoordinator){
if let controller = landscapeViewController{
controller.willMoveToParentViewController(nil)
coordinator.animateAlongsideTransition({ _ in
controller.view.alpha = 0
}, completion: { _ in
if self.presentedViewController != nil {
self.dismissViewControllerAnimated(true, completion: nil)
}
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
self.landscapeViewController = nil
})
}
}
private func showNetworkError(){
let alert = UIAlertController(title: "Whoops...", message: "There was an error reading from the iTunes Store. Please try again.", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
// MARK: Detail ViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowDetail" {
switch search.state{
case . Results(let list):
let indexPath = sender as! NSIndexPath
let searchResult = list[indexPath.row]
let detailViewController = segue.destinationViewController as! DetailViewController
detailViewController.searchResult = searchResult
default:
break
}
}
}
// MARK: Properties
#IBOutlet weak var searchBar: UISearchBar!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var segmentedControl: UISegmentedControl!
let search = Search()
private var landscapeViewController: LandscapeViewController?
// MARK: Methodes
#IBAction func segmentedControl(sender: UISegmentedControl) {
performSearch()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsets(top: 108, left: 0, bottom: 0, right: 0)
tableView.rowHeight = 80
searchBar.becomeFirstResponder()
configureNib(nibName: TableViewCellIdentifier.searchResultCell)
configureNib(nibName: TableViewCellIdentifier.nothingFoundCell)
configureNib(nibName: TableViewCellIdentifier.loadingCell)
}
private func configureNib(nibName nibName: String){
let cellNib = UINib(nibName: nibName, bundle: nil)
tableView.registerNib(cellNib, forCellReuseIdentifier: nibName)
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar){
performSearch()
}
private func performSearch() {
if let category = Search.Category(rawValue: segmentedControl.selectedSegmentIndex){
search.performSearchForText(searchBar.text!, category: category){
success in
if !success{
self.showNetworkError()
}
if let controller = self.landscapeViewController{
controller.searchResultsRecived()
}
self.tableView.reloadData()
}
tableView.reloadData()
searchBar.resignFirstResponder()
}
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
// MARK: TableView
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch search.state{
case .NotSearchedYet:
return 0
case .Loading,.NoResults:
return 1
case .Results(let list):
return list.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch search.state{
case .NotSearchedYet:
fatalError("Should never get here")
case .Loading:
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.loadingCell, forIndexPath: indexPath)
let spinner = cell.viewWithTag(100) as! UIActivityIndicatorView
spinner.startAnimating()
return cell
case .NoResults:
return tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.nothingFoundCell, forIndexPath: indexPath)
case .Results(let list):
let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifier.searchResultCell, forIndexPath: indexPath) as! SearchResultCell
let searchResult = list[indexPath.row]
cell.configureForSearchResult(searchResult)
return cell
}
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
performSegueWithIdentifier("ShowDetail", sender: indexPath)
}
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
switch search.state{
case .NotSearchedYet,.NoResults,.Loading:
return nil
case .Results:
return indexPath
}
}
}
This is a bug in the Swift compiler, you'll want to file a radar with Apple to report this. There's nothing you can do about it otherwise.
I had this error because I had a switch of an enum with a case that contain an Array payload (don't ask me why, I don't know).
I think the enum is the search state inside the tableView:cellForRowAtIndexPath: method of SearchViewController and the prepareForSegue: method of LandscapeViewController (the .Result case contain a list).
In my case, changing the payload to a Set instead of an Array worked. (as a workaroud until it's fixed)

Resources