I've been developing a share extension for my iOS app with a custom view controller. The custom view controller has an ImageView, a label and a textBox. I want to get the url from the webpage where the user tries to share with my app and set it as the text of the label. But when I try to get access to the label, it is nil. I've been trying this operation in diferente lifecycle methods, as viewDidLoad()
, viewWillLoad()
and finally I use viewDidAppear()
but the result it's the same. The elements are properly connected in the storyboard to the Viewcontroller:
Here it's my ViewController code:
import UIKit
import Social
class ShareViewController: UIViewController {
@IBOutlet var ScreenCapture: UIImageView!
@IBOutlet var articleTitle: UITextField!
@IBOutlet var urlLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let item = extensionContext?.inputItems.first as? NSExtensionItem {
if let attachments = item.attachments {
for attachment: NSItemProvider in attachments {
if attachment.hasItemConformingToTypeIdentifier("public.url") {
attachment.loadItem(forTypeIdentifier: "public.url", options: nil, completionHandler: { (url, error) in
if let shareURL = url as? URL {
self.urlLabel.text = shareURL.absoluteString
}
})
}
}
}
}
}
@IBAction func cancelShare(_ sender: Any) {
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
@IBAction func doneShare(_ sender: Any) {
//TODO: Insert into CoreData
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
}
I put a breakpoint in the self.urlLabel.text = shareURL.absoluteString
line and here it's the debugger information:
EDIT: Finally I solved my issue, I must call loadViewIfNeeded()
:
override func loadViewIfNeeded() {
super.loadViewIfNeeded()
let image = makeScreenShoot(withView: view)
if let item = extensionContext?.inputItems.first as? NSExtensionItem {
if let attachments = item.attachments {
for attachment: NSItemProvider in attachments {
if attachment.hasItemConformingToTypeIdentifier("public.url") {
attachment.loadItem(forTypeIdentifier: "public.url", options: nil, completionHandler: { (url, error) in
if let shareURL = url as? URL {
self.urlLabel.text = shareURL.absoluteString
}
})
}
}
}
}
ScreenCapture.image = image
}