osx - Get data from HTTP Request - Swift -
osx - Get data from HTTP Request - Swift -
today i'm trying info webpage.
it keeps crashing saying "exc bad access", suggestion ?
class codeviewcontroller: nsobject { @iboutlet var output_box : nstextfield @iboutlet var url_textfield : nstextfield var output : nsstring = "unable load data" func downloadhtml (path: string) -> string { var url = nsurl(string: "\(path)") var request = nsurlrequest(url: url) nsurlconnection.sendasynchronousrequest(request, queue: nsoperationqueue.mainqueue()) {(response, data, error) in self.output = nsstring(data: data, encoding: nsutf8stringencoding) //exc_bad_access when trying set self.output new value } homecoming output } @ibaction func retrive(sender: anyobject!) { println(downloadhtml(url_textfield.stringvalue)) } }
i suspect "url_textfield.stringvalue" nil @ point pass in. trying fixed string works. note function homecoming before async request completes, , code print "unable load". if add together line assigns output output_box in completion handler, see the text box update 1 time request completes...
the code tried, works, is...
class codeviewcontroller: nsobject { var output : nsstring = "unable load data" func downloadhtml (path: string) -> string { var url = nsurl(string: "\(path)") var request = nsurlrequest(url: url) allow completionblock: (nsurlresponse!, nsdata!, nserror!) -> void = {response, data, error in self.output = nsstring(data: data, encoding: nsutf8stringencoding) println("asynch completed \(self.output)") } nsurlconnection.sendasynchronousrequest(request, queue: nsoperationqueue.mainqueue(), completionhandler: completionblock) homecoming output } } var c: codeviewcontroller? = nil c = codeviewcontroller() c!.downloadhtml("http://www.google.com") println("immediate \(c!.output)")
and output is:
immediate unable load data asynch completed <!doctype html><html ...
osx swift xcode6
Comments
Post a Comment