xcode


NSURLSessionDataTask: func receives but returns no data


I've tried to create a simple function which receives URL and simply returns the HTML of the webpage. the NSURLSessionDataTask itself seems to work, I can see the whole html when I println(data). But the func only returns the initial value "#!?". I suspect that the DataTask works asynchronous? How can I handle this?
func loadHTML(targetURL: String) -> String {
var theTargetURL = NSURL(string:targetURL)
var theResult = "#!?"
var request: NSURLRequest = NSURLRequest(URL:theTargetURL)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
println(NSString(data: data, encoding: NSASCIIStringEncoding))
if error != nil {
println(error.localizedDescription)
theResult = "error"
}
if data != nil {
theResult = NSString(data: data, encoding: NSASCIIStringEncoding)
println("RECEIVED\t\t\(countElements(theResult)) CHARS")
}
});
task.resume()
return theResult
}
Here is an example how you would do it using a completion handler.
typealias CompletionBlock = (NSData!, NSURLResponse!, NSError!) -> Void
func loadHtml(targetUrlString: String, completion: CompletionBlock){
let targetUrl = NSURL(string: targetUrlString)
let request = NSURLRequest(URL: targetUrl)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: completion)
task.resume()
}
Then, call it from your method where it is needed,
func viewDidLoad(){
super.viewDidLoad()
loadHtml("http://google.com", completion: { (responseData: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if responseData != nil{
let resultString = NSString(data: responseData, encoding: NSASCIIStringEncoding)
println(resultString)
/*
do some task or update on the main thread
dispatch_async(dispatch_get_main_queue){
myActivityIndicator.stopAnimating()
}
*/
}else if error != nil{
println("Error occurred: \(error.localizedDescription)")
}
})

Related Links

Xcode git not showing xcassets to commit
How to enable horizontal scrolling of text in NStextView window for OSX application?
How to prevent the Apple Watch from going to sleep?
xcode 7.3 can not find glances in my watch
Plotting multiple scatter lines in different rate?
Swift 3D Touch Quick Action not loading requested url
What is the default design size for Xcode storyboard?
UIImageView in table cell is not staying within frame original frame?
xCode 7: how to fix initialization of variable was never used consider replacing with assignment to '_' or removing it
Xcode Core Data models are missing
How to auto implement protocol methods in Xcode?
SQLite and Sandboxed OSX apps
Xcode 7.2: how to build with Ad Hoc provisioning profile vs. App Store provisioning profile?
Can't get location on device in Swift
Adding PayPal to IOS brings up many errors With Facebook SDK
Do something on button click inside of footer in a tableView

Categories

HOME
rust
extjs
xcode8.1
schema.org
celery
qooxdoo
hyperledger
turbojpeg
port
eddystone
stack-overflow
clickable-image
tiff
google-awareness
fresco
playframework-2.0
checkout
cloudsim
akka-persistence
backtracking
channel
environment
cellular-network
sap-lumira
network-analysis
ruby-daemons
microprocessors
javax.persistence
jsonresult
progid
delayed-job
epplus
overwrite
cloudera-manager
bootstrap-sass
creation
busboy
assertions
redgate
django-crispy-forms
cloudera-quickstart-vm
mars-simulator
stat
swfupload
python-jira
vb.net-to-c#
hypothesis-test
robust
ipp-protocol
liteide
cyanogenmod
tinyioc
subforms
webvtt
palindrome
popen
.when
instafeedjs
email-injection
elastic4s
okio
logical
livecycle
always-on-top
raw-sockets
meld
gnucash
codecharge
rails-engines
mathnet
vaadin4spring
okta-api
voronoi
enunciate
grinder
cryptojs
openshift-cartridge
hmisc
darwin
bootstrap-wysiwyg
ipod
scala-macros
text-align
angular-ui-select
windows-messages
hyperloglog
commenting
xmi
jchartfx
assetic
apache-shindig
grails-2.3
mousemotionlistener
mute
rautomation
form-for
ldif
sly-scroller
html-frames
tfs-sdk
dojo-1.9
clearinterval
first-class
kaazing
background-repeat
groovy-console
reliability
cleartype
yahoo-maps
ppc
spring-modules
powergui
server-load
isapi-redirect
chronic

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App