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

How to prevent Xcode 3.2.5 to not show those blue message bubbles when debugging?
How to Turn a View into Landscape Mode in Xcode 4
XCode- Need Help With Errors (Expected ; and Expected Statement)
How to set up SDL on XCODE 4?
xcode 4 add CoreData in a existing project
How can I find my application's resource group/map in XCode?
iOS Architecture and Xcode Organiser window
How to save the option selected in UIPickerView and Load it back up
SecTrustedApplicationCreateFromPath being too smart?
How to quickly remove all the unused variables with xCode?
Xcode keeps guessing and interpreting with wrong encoding
XCode - File not found but build successful
How do you manage the events in a UINavigationController view to switch views?
xcode crashes all the time !
Can app preferences be read only on startup?
“Combine High Resolution Artwork” in XCode 4?

Categories

HOME
php
qt
nam
protocol-buffers
yii
long-integer
bots
dependencies
google-sheets-query
turbojpeg
drag-and-drop
bittorrent
fedora
ag-grid
gprs
anchor
azure-logic-apps
bootstrap-switch
fresco
google-cloud-logging
l20n
scala-ide
exec-maven-plugin
anova
dashdb
pst
react-dnd
basex
docx4j
copy-protection
snap-framework
overwrite
nest
cargo
flowchart
grails3.2.0
hdiv
fiware-wirecloud
git-tfs
audio-converter
sonarqube5.2
sharpdx
android-webservice
watir-webdriver
google-news
portability
alertify
swiperefreshlayout
msxml
ltrace
nrf51
boost-compute
metabase
xcode6.4
system.web.optimization
jenkins-workflow
cdo.message
maven-release-plugin
eclemma
android-syncadapter
facebook-ios-sdk
jemdoc
gulp-uglify
stack-smash
bjam
vdm-sl
flow-js
mgwt
mxe
ssmtp
thoughtworks-go
squeezebox
jini
prism.js
jms-serializer
nosql-aggregation
lync-2010
strdup
armv6
hyphen
application-server
aero
days
xcode4.5
nsmutablestring
word-frequency
java.lang.class
groovy-console
startupscript
kext
dip
resharper-5.1
activestate
ppc
downcasting
database-cloning
jboss-mdb
regioninfo

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App