Add A Callback To A Prebuilt Asynchronous Function Swift iOS -
i'm messing around pdfs @ moment. i'm attempting load pdf system , write out same pdf gain understandings of the whole procedure.
the problem i've got i'm having load pdf web , because webviewui.loadrequest asynchronous, isn't completed in time.
override func viewdidload() { super.viewdidload() let filepath = getdocumentsdirectory().stringbyappendingpathcomponent("output.pdf") let url : nsurl! = nsurl(string: "http://www.nhs.uk/nhsengland/healthcosts/documents/2014/hc5(t)%20june%202014.pdf") loadtemplate(url, completion: {(webview: uiwebview) -> void in print("callback started") let pdf = self.topdf(webview) { pdf!.writetofile(filepath, atomically: true) } catch { // failed write file – bad permissions, bad filename, missing permissions, or more can't converted encoding } print("callback started") }) print("finished viewdidload") } func loadtemplate(url: nsurl, completion: (webview: uiwebview) -> void) { print("start loadtemplate") // crunching create sketchanimation instance... let webview = uiwebview(frame: cgrectmake(20, 100, 300, 40)) webview.loadrequest(nsurlrequest(url: url)) self.view.addsubview(webview) // invoke completion callback completion(webview: webview) print("finished loadtemplate") }
how add callback loadrequest instead of loadtemplate?
you don't, exactly. you'd set view controller web view's delegate , implement webviewdidfinishload
method. in method you'd check make sure load finished 1 after, , if so, you'd invoked code want run when load complete.
here basic example of how set up:
// // viewcontroller.swift // import uikit class viewcontroller: uiviewcontroller, uiwebviewdelegate { @iboutlet var webview: uiwebview! var url = nsurl(string: "http://google.com") override func viewdidload() { super.viewdidload() //load initial url let req = nsurlrequest(url : url!) webview.delegate = self webview.loadrequest(req) } func webviewdidstartload(webview : uiwebview) { print("aa") } func webviewdidfinishload(webview : uiwebview) { print("bb") } }
Comments
Post a Comment