using the activityController to share label - ios

I have the following code
let textToShare = "Check out the test original for \(String(describing: bookTitle.text))"
if let myWebsite = URL(string: "X") {//Enter link to your app here
let objectsToShare = [textToShare, myWebsite] as [Any]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
//Excluded Activities
activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, UIActivity.ActivityType.addToReadingList]
activityVC.popoverPresentationController?.sourceView = sender
self.present(activityVC, animated: true, completion: nil)
}
When i try to share the label text bookTitle.text, I get the output Optional("Test"). Is there a way to share UILabel text using the UIActivityViewController?

I get the output Optional("Test")
Actually, you're in the right way. Except you need to "unwrap" that optional property .text. You can do it in so many ways. One way is to force unwrap it (not recommended most of the time!) Like so:
let textToShare = "Check out the test original for \(bookTitle.text!)"
Or one more way is to use nil coalescing. Like so:
let textToShare = "Check out the test original for \(bookTitle.text ?? "")"
More about Optional Chaining https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html
P.S no need to use String(describing:). You use it usually in print().

Related

ios - format the information shared with share sheet

I am using the following code to present a share sheet:
let url = "https://somelink.com"
let image = "https://myserver/an_image.png"
let text = "Join now!"
let shareSheetVC = UIActivityViewController(activityItems: [image, url, text], applicationActivities: nil)
shareSheetVC.popoverPresentationController?.sourceView = sender
shareSheetVC.popoverPresentationController?.sourceRect = sender.frame
present(shareSheetVC, animated: true)
What I'd like is something like this:
However, when I share I just get
https://somelink.com
https://myserver/an_image.png
Join now!
How can I format this to accomplish something like the example?
This is the basic example to share Text, Image and URL using UIActivityViewController
let text = "Join Now!"
let image = UIImage(named: "your_image")
let myWebsite = URL(string: "https://somelink.com")
let shareAll = [text , image! , myWebsite]
let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.popoverPresentationController?.sourceRect = sender.frame
self.present(activityViewController, animated: true, completion: nil)
Hope you understand.
Alternatively, you could approach this from a different angle and try to fix your webpage by adding:
<meta property="og:image" content="https://myserver/an_image.png">
<title>Join now!</title>
Those tags will be picked up by default from the UIActivityViewController.

How to make URL String with linkable when sharing it

When sharing URL String via email WhatsApp other sharable component its url formate is not linkable with underline
let encodedStr = dict!.base64EncodedString()
let appLink = "https://companyName.com/account/signupbyinvite?\(encodedStr)"
When sharing via email message box the url formate is not clickable and underline below like is not visible.
convert the url string in to url
guard let appUrl = URL(string : appLink) else {return}
then share with uiactivitycontroller link will auto clickable once its shared. like this
let activityViewController = UIActivityViewController(activityItems: [appUrl], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)

Save image to library from URL, rename, and share it using Swift

I want to share images to Instagram from my own iOS app and I am using Kingfisher throughout the project to download and cache images and show them in UIImageViews but this time I want to do something a little bit different.
Basically, I am getting a response from an API with the url of an image and I want to
Download the image to the library using the URL
There is a bunch of questions on this for objective-C using
UIImageWriteToSavedPhotosAlbum
but I am using Swift.
Rename it with .igo extension (instagram exclusive)
Not sure how to go about this, would depend on number 1.
Then I could share it doing something like
let image = UIImage(named: "downloadedImage")
let objectsToShare: [AnyObject] = [ image! ]
let activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.excludedActivityTypes = [ UIActivityTypeAirDrop, UIActivityTypePostToFacebook ]
self.presentViewController(activityViewController, animated: true, completion: nil)
or I could do it using the instagram hooks:
instagram://library?LocalIdentifier=\(localID)
Documentation on this is scarce specially for Swift. How can I go about this? a push in the right direction is all I need.
It sounds like you already know how to use Kingfisher and retrieving the UIImage from the URL. So what i'm about to provide is information for saving the image to the documents directory and retrieving it to share.
Retrieve the correct directory URL
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
Saving an image to that directory
func saveImage (image: UIImage, filename: String ){
print("Saving image with name \(filename)")
if let data = UIImagePNGRepresentation(image) {
let fullURL = getDocumentsDirectory().appendingPathComponent(filename)
try? data.write(to: fullURL)
}
}
Retrieving an image from the directory
func loadImageFromName(name: String) -> UIImage? {
print("Loading image with name \(name)")
let path = getDocumentsDirectory().appendingPathComponent(name).path
let image = UIImage(contentsOfFile: path)
if image == nil {
print("missing image at: \(path)")
}
return image
}
Sharing an image
func share(shareText shareText:String?,shareImage:UIImage?){
var objectsToShare = [AnyObject]()
if let shareTextObj = shareText{
objectsToShare.append(shareTextObj)
}
if let shareImageObj = shareImage{
objectsToShare.append(shareImageObj)
}
if shareText != nil || shareImage != nil{
let activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
present(activityViewController, animated: true, completion: nil)
}else{
print("There is nothing to share")
}
}
How to Use
let img: UIImage = UIImage() // Replace this with your image from your URL
saveImage(image: img, filename: "newImage.igo") //This is where you change your extension name
let newImage: UIImage = loadImageFromName(name: "newImage.igo") //Retrieve your image with the correct extension
share(shareText: "Image going to Instagram", shareImage: newImage) //Present Activity VC.
And as DFD pointed out, you can exclude certain items from the share VC to only allow what you need.
In my navigation controller, I have a UIBarButtonItem set to System item "Action". I then created the following IBAction code:
#IBAction func shareImage(_ sender: UIBarButtonItem) {
let context = CIContext()
let final = context.createCGImage(imgFinished, from: imgFinished.extent)
let shareImage = UIImage(cgImage: final!)
let vc = UIActivityViewController(activityItems: [shareImage], applicationActivities: [])
vc.excludedActivityTypes = [
UIActivityType.airDrop,
UIActivityType.assignToContact,
UIActivityType.addToReadingList,
//UIActivityType.copyToPasteboard,
//UIActivityType.mail,
//UIActivityType.message,
//UIActivityType.openInIBooks,
//UIActivityType.postToFacebook,
//UIActivityType.postToFlickr,
UIActivityType.postToTencentWeibo,
//UIActivityType.postToTwitter,
UIActivityType.postToVimeo,
UIActivityType.postToWeibo,
UIActivityType.print,
//UIActivityType.saveToCameraRoll
]
present(vc,
animated: true,
completion: nil)
vc.popoverPresentationController?.sourceView = self.view
vc.completionWithItemsHandler = {(activity, success, items, error) in
}
}
The excludedActivityTypes list is a complete/exhaustive list of available UIActivityTypes gleaned from code-complete or command-clicking on UIActivity type and going through the resulting struct. I uncomment those I wish to exclude - but leave them in for quick reference in the future. This will give you the popup you want.

How Can I share text and Image Together on Whatsapp

I want to share image and text together with swift.How Can I do That ?
let url = NSURL(string: "whatsapp://app")
let shareText = "Beni Bons'da ekle : \(PFUser.currentUser()!.username!). http://apple.co/29RMfNn"
let bonsCardImage = UIImage.renderUIViewToImage(bonsCardView)
let activityItems = [bonsCardImage]
let vc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
presentViewController(vc, animated: true, completion: nil)
Thanks

UIActivityViewController is always sharing image before text

In my app, I want to share the current song and artist followed by the album artwork. Here is my code:
var sharingItems = [AnyObject]()
let currentSong = musicPlayer.nowPlayingItem?.title
let currentArtist = musicPlayer.nowPlayingItem?.artist
let artwork = musicPlayer.nowPlayingItem?.artwork
let artworkImage = artwork?.imageWithSize(CGSizeMake(100, 100))
let shareText = "Now playing \(currentSong!) by \(currentArtist!) via Ryan's awesome app"
sharingItems.append(shareText) //text first, then image
sharingItems.append(artworkImage!)
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivityTypeAddToReadingList, UIActivityTypeAssignToContact, UIActivityTypeOpenInIBooks, UIActivityTypePrint, UIActivityTypeSaveToCameraRoll]
self.presentViewController(activityViewController, animated: true, completion: nil)
When I choose a share option, like Messges, the image is before the text in the TextField. Why is the image first if it's last in the array?

Resources