Shared Text doesn't get shared to Facebook (but to others) - xcode

I have this code that shares a screenshot of the app, an initial Text and a URL via the Apple Share menu when a Share Button is pressed. It works like a charm with Twitter, Messages, Email etc, but when i wanna share to Facebook or the Facebook Messenger, the text doesn't show up (but the image and the URL do).
Any idea why that is and how to fix it?
I was able to share text and a URL to Facebook with other functions (but they didn't deliver the right screenshot so i switched to this one).
Thanks in advance!
Edit: The text does get shared in the xcode Simulator, just not on the iPhone(s).
func takeSnapshot(view: UIView) {
let bounds = UIScreen.mainScreen().bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
self.view.drawViewHierarchyInRect(bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let text = "Text to be shared... #Hashtag"
let URL = NSURL(string: "http://stackoverflow.com/")!
let activityViewController = UIActivityViewController(activityItems: [image, text, URL], applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}

An update to the Facebook application has replaced the in-built Facebook share activity with one that ignores status text - If you remove the Facebook app from your device the text will be displayed using the code you have. If you have the Facebook app installed you get images, URLs but not the text.
Follow the instructions: https://developers.facebook.com/docs/sharing/ios
Then you can do something like this:
Share a link
let content : FBSDKShareLinkContent = FBSDKShareLinkContent()
content.contentURL = NSURL(string: "<INSERT STRING HERE>")
content.contentTitle = "<INSERT STRING HERE>"
content.contentDescription = "<INSERT STRING HERE>"
content.imageURL = NSURL(string: "<INSERT STRING HERE>")
let button : FBSDKShareButton = FBSDKShareButton()
button.shareContent = content
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 100) * 0.5, 50, 100, 25)
self.view.addSubview(button)
Share Photos
class ViewController: UIViewController, FBSDKLoginButtonDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate
let button : UIButton = UIButton()
button.backgroundColor = UIColor.blueColor()
button.setTitle("Choose Photo", forState: .Normal)
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 150) * 0.5, 125, 150, 25)
button.addTarget(self, action: "photoBtnClicked", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
let label : UILabel = UILabel()
label.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 200) * 0.5, 100, 200, 25)
label.text = "Photos Example"
label.textAlignment = .Center
self.view.addSubview(label)
func photoBtnClicked(){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){
println("Photo capture")
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let photo : FBSDKSharePhoto = FBSDKSharePhoto()
photo.image = info[UIImagePickerControllerOriginalImage] as! UIImage
photo.userGenerated = true
let content : FBSDKSharePhotoContent = FBSDKSharePhotoContent()
content.photos = [photo]
}
Photos must be less than 12 MB in size
Share Video on Facebook
class ViewController: UIViewController, FBSDKLoginButtonDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate
let button : UIButton = UIButton()
button.backgroundColor = UIColor.blueColor()
button.setTitle("Choose Video", forState: .Normal)
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 150) * 0.5, 200, 150, 25)
button.addTarget(self, action: "videoBtnClicked", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
let label : UILabel = UILabel()
label.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 200) * 0.5, 175, 200, 25)
label.text = "Video Example"
label.textAlignment = .Center
self.view.addSubview(label)
func videoBtnClicked(){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSource Type.SavedPhotosAlbum){
println("Video capture")
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let video : FBSDKShareVideo = FBSDKShareVideo()
video.videoURL = info[UIImagePickerControllerMediaURL] as! NSURL
let content : FBSDKShareVideoContent = FBSDKShareVideoContent()
content.video = video
}
Videos must be less than 12MB in size. I hope I have helped you. (Sorry for my english)

Related

UIImage inside UIImageView is not scalling to fit

I receive a high resolution images from API, and I need to scale to fit them to my collection view cells. I'm using scaleToFit in UIImageView init but images are still in original ratio, moreover if I start to scroll in some moment they will get in full size
Cell:
final class SnapCarouselCellImpl: UICollectionViewCell, SnapCarouselCell{
var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleToFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
imageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
}
VC:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SnapCarouselCell", for: indexPath) as! SnapCarouselCellImpl
let item = items[indexPath.row % items.count]
cell.imageView.image = UIImage(data: item.poster)
return cell
}
private func setUpCollectionView() -> UICollectionView{
let collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: flowLayout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.frame = CGRect(x: 0, y: 100, width: view.frame.size.width, height: cellHeight * 1.2)
collectionView.decelerationRate = .init(rawValue: 20)
collectionView.register(SnapCarouselCellImpl.self, forCellWithReuseIdentifier: "SnapCarouselCell")
return collectionView
}
FlowLayout:
override func prepare() {
scrollDirection = .horizontal
minimumLineSpacing = 20
itemSize = CGSize(width: cellWidth, height: cellHeight)
let sideMargin = (collectionView!.bounds.width - cellWidth) / 2.0
sectionInset = UIEdgeInsets(top: 0.0, left: sideMargin, bottom: 0.0, right: sideMargin)
}
Result:
After scrolling:
You didn't provide enough code to confirm this, but...
You can probably correct the issue by changing this line in init in your SnapCarouselCellImpl class from:
addSubview(imageView)
to:
contentView.addSubview(imageView)

macOS NSPopover menu bar app how to prioritize order app is displayed

I have a macOS menu bar app. I like to know can we prioritize the order that the app shows in the status bar.
//
// AppDelegate.swift
// elmc_midi_deck-macOS
//
// Created by Jerry Seigle on 6/23/22.
//
import Foundation
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var popover: NSPopover!
var window: NSWindow!
var statusBarItem: NSStatusItem!
func applicationDidFinishLaunching(_ aNotification: Notification) {
let jsCodeLocation: URL
#if DEBUG
jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index", fallbackResource:nil)
#else
jsCodeLocation = Bundle.main.url(forResource: "main", withExtension: "jsbundle")!
#endif
let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "elmc_midi_deck", initialProperties: nil, launchOptions: nil)
let rootViewController = NSViewController()
rootViewController.view = rootView
popover = NSPopover()
popover.contentSize = NSSize(width: 400, height: 600)
popover.animates = true
popover.behavior = .transient
popover.contentViewController = rootViewController
statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(60))
if let button = self.statusBarItem.button {
button.action = #selector(togglePopover(_:))
button.title = "elmc_midi_deck"
}
#if DEBUG
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 1, height: 1),
styleMask: [.titled, .closable, .miniaturizable, .resizable],
backing: .buffered,
defer: false)
window.contentViewController = rootViewController
window.center()
window.setFrameAutosaveName("ELMC Midi Deck")
window.isReleasedWhenClosed = false
window.makeKeyAndOrderFront(self)
let screen: NSScreen = NSScreen.main!
let midScreenX = screen.frame.midX
let posScreenY = 200
let origin = CGPoint(x: Int(midScreenX), y: posScreenY)
let size = CGSize(width: 400, height: 600)
let frame = NSRect(origin: origin, size: size)
window.setFrame(frame, display: true)
#endif
}
#objc func togglePopover(_ sender: AnyObject?) {
if let button = self.statusBarItem.button {
if self.popover.isShown {
self.popover.performClose(sender)
} else {
self.popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
self.popover.contentViewController?.view.window?.becomeKey()
}
}
}
}
Currently the app will show at the far left once started. Of course you can command click and drag left to right but I like to make the app show after Apple's default apps like show in the photo
As mentioned in this post, you can use this library to do this. The library allows defining the position for an NSStatusBarItem inside the NSStatusBar. It is written in Objective-C and available via CocoaPods, you probably have to create a bridging header or manually convert it in order to use it in Swift. Refer to this post for details on how to do this.

UISwitch set on/off Image

I want to set my Switch like this:
But I try in ios9 , it does not work.
I saw in apple UISwitch Class Reference.
It says that :
Discussion
In iOS 7, this property has no effect.
How about iOS 9? Any one success?
My Code:
switch1 = UISwitch(frame:CGRectMake(self.view.frame.width/2 - 20, 400, 10, 100))
switch1.on = true
switch1.onTintColor = UIColor.lightGrayColor()
switch1.tintColor = UIColor.greenColor()
switch1.thumbTintColor = UIColor.blackColor()
//set on/off image
switch1.onImage = UIImage(named: "on-switch")
switch1.offImage = UIImage(named: "off-switch")
Use a UIButton instead.
let switchButton = UIButton(type: .Custom)
switchButton.selected = true
switchButton.setImage(UIImage(named: "on-switch"), forState: .Selected)
switchButton.setImage(UIImage(named: "off-switch"), forState: .Normal)
Use switchButton.isSelected instead of switch1.on. You'll have to toggle switchButton.isSelected when it is tapped, which you can do like this:
switchButton.isSelected.toggle()
For iOS 13, you could do this way:
let switcher = UISwitch()
switcher.addTarget(self, action: #selector(pressed), for: .valueChanged)
#objc func pressed(sender: UISwitch) {
let color = UIColor(patternImage: UIImage(named: sender.isOn ? "on.png": "off.png")!)
if sender.isOn {
sender.onTintColor = color
} else {
sender.tintColor = color
sender.subviews[0].subviews[0].backgroundColor = color
}
}
NOTE: your image should look like:
Then the final result is:
Not an exact answer to your question, but if you want a completely custom button switch programmatically (that you can add text to), this will work too:
import UIKit
class RDHiddenVisibleButton: UIButton {
// Hidden / Visible Button Function
var isOn = false
override init(frame: CGRect) {
super.init(frame: frame)
initButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initButton()
}
func initButton() {
layer.borderWidth = 2.0
layer.borderColor = Colors.radiusGreen.cgColor
layer.cornerRadius = frame.size.height/2
setTitleColor(Colors.radiusGreen, for: .normal)
addTarget(self, action: #selector(RDHiddenVisibleButton.buttonPressed), for: .touchUpInside)
}
#objc func buttonPressed() {
activateButton(bool: !isOn)
}
func activateButton(bool: Bool) {
isOn = bool
let color = bool ? Colors.radiusGreen : .clear
let title = bool ? "Hidden" : "Visible"
let titleColor = bool ? . white : Colors.radiusGreen
setTitle(title, for: .normal)
setTitleColor(titleColor, for: .normal)
backgroundColor = color
}
}

Xcode Swift image zoom gesture

Hope someone can help me. Im trying to make a zoom gesture, so when the image are presented the user can zoom the image with fingers.
My code to present the image are:
// MARK: Show image full screen
func imageTapped(img: AnyObject) {
self.navigationController?.navigationBarHidden = true
let imageView = productImage as UIImageView
let newImageView = UIImageView(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = .blackColor()
newImageView.contentMode = .ScaleToFill
newImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: "dismissFullscreenImage:")
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
func dismissFullscreenImage(sender: UITapGestureRecognizer) {
sender.view?.removeFromSuperview()
self.navigationController?.navigationBarHidden = false
}
Use UIScrollView and add UIImgeView in scroll view
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate
{
var scrollV : UIScrollView!
var imageView : UIImageView!
override func viewDidLoad()
{
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true
scrollV=UIScrollView()
scrollV.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
scrollV.minimumZoomScale=1
scrollV.maximumZoomScale=3
scrollV.bounces=false
scrollV.delegate=self;
self.view.addSubview(scrollV)
imageView=UIImageView()
imageView.image = UIImage(imageLiteral: "neymar.jpg")
imageView.frame = CGRectMake(0, 0, scrollV.frame.width, scrollV.frame.height)
imageView.backgroundColor = .blackColor()
imageView.contentMode = .ScaleToFill
scrollV.addSubview(imageView)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
{
return imageView
}
}
Take gesture programmatically and make its method and write down this code in the method.
pinchRecognizerOnView() is my method name. Take one view or image view inside view controller and add this new view in that.Now apply gesture method on this new view.
func pinchRecognizerOnView(sender: UIPinchGestureRecognizer!) {
sender.view?.transform = CGAffineTransformScale((sender.view?.transform)!, sender.scale, sender.scale)
sender.scale = 1
// its for zoom in out screen
}

From SWIFT Playground to custom View (IBDesignable?)

Question:
I've written a custom View Component in a playground but I can't figure out how to turn it into a custom class that I can use in the Interface Builder. Specifically, I'm confused as to how to make sure my custom view will resize correctly as the IB view is changed
Sub Question
I would also like to be able to use the #IBDesignable/#IBInspectable functionality as well if possible
Playground Code
import UIKit
let labelWidth : CGFloat = 200.0
var viewWidth : CGFloat = 200.0
let labelHeight: CGFloat = 60.0
var viewHeight : CGFloat = 60.0
let xOffset : CGFloat = 20
let yOffset : CGFloat = 20
let label = UILabel(frame: CGRectMake(0, 0 + 10, labelWidth, 50))
label.text = "Custom Text"
label.backgroundColor = UIColor.greenColor()
label.layer.masksToBounds = true
//label.layer.cornerRadius = 10.0
label.textAlignment = NSTextAlignment.Center
label
let titleLabel = UILabel(frame: CGRectMake(0,0,labelWidth,20))
titleLabel.font = UIFont(name: label.font.fontName, size: 10)
titleLabel.text = " TITLE"
titleLabel.layer.masksToBounds = true
titleLabel.backgroundColor = UIColor.whiteColor()
titleLabel
let v = UIView(frame: CGRectMake(0, 0, viewWidth, viewHeight))
v.backgroundColor = UIColor.grayColor()
v.addSubview(label)
v.addSubview(titleLabel)
v.layer.borderWidth = 1
v.layer.borderColor = UIColor.redColor().CGColor
v
Playground Visual Output
Note: Obviously these are not the final colors i want to use but they help differentiate the components
I just posted this answer for a similar question.
Here is a sample class to get you started.
import UIKit
#IBDesignable
class MyTabView: UIView {
#IBInspectable tabTitle: String = ""
#IBInspectable tabColor: UIColor = UIColor.clearColor()
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForInterfaceBuilder() {
// stuff for interface builder only
}
override func drawRect(rect: CGRect)
{
// this is where your view gets drawed
self.layer.cornerRadius = 10
self.layer.masksToBounds = true
}
}
Note: you only need to override drawRect if you need custom drawing.

Resources