Warhost Warhost - 3 months ago 18
Swift Question

Convert String or NSUrl in order to use in UIActivityViewController

I am a bit lost with optionals, AnyObjects and Strings. I have an application where I simply want to open the ActivityController when a button is pressed. Given a URL, several options to share the URL should come up then.
I couldn't find a way yet in which it works, either Xcode says it can't convert to AnyObject, or I'm getting nil.

What is the proper way of doing this?
What I have so far:

let data = snap.value as! [String : AnyObject] //Getting a snapshot from Firebase

let dataurl = data["url"] as! String //Prefix is url, this gives just the URL
let dataurlstring = NSURL(string: dataurl!)

let activityVC = UIActivityViewController(activityItems: dataurlstring, applicationActivities: nil)

Answer

Can you try this and let me know if it works for you? It's not a proper answer but just a starting point to fix it:

func showAlert(with snapValues: [String: AnyObject]?) {
    guard let snapValues = snapValues, let dataurl = snapValues["url"] as? String, let dataurlstring = NSURL(string: dataurl) else {
        return
    }

    let activityVC = UIActivityViewController(activityItems: [dataurlstring], applicationActivities: nil)
    //Continue to show the alert or return the object activityVC 
}

and the call it like this:

let snapValues = snap.value as? [String : AnyObject]
showAlert(with: snapValues)

if you want to avoid the optional parameter in the function change the code like this:

  1. Function:

    func showAlert(with snapValues: [String: AnyObject]) {
        guard let dataurl = snapValues["url"] as? String, let dataurlstring = NSURL(string: dataurl) else {
                return
        }
        ....
    }
    
  2. Call:

    if let snapValues = snap.value as? [String : AnyObject] {
        showAlert(with: snapValues)
    }