I am trying to use a NSURLSession to pull some data from espn, but I can't seem to get it to work. It prints only nil.
I've tested this method with another page on their website and it worked, but I can't get it to work with the one in the code. Here is the code in question:
var url = NSURL(string: "http://espn.go.com/golf/leaderboard?tournamentId=2271")
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
print(data)
if error == nil {
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!
print(urlContent)
I've also tried changing the encoding type which didn't work either. The data it's printing looks like it's UTF 8 format, so I didn't think that would work but felt I should try.
I feel like I've run out of ideas to work.
Edit : Should have specified more, print(data) prints out what I expected, encoded data, but print(urlContent) prints nil.
Here's the full example that works
var url = NSURL(string: "http://espn.go.com/golf/leaderboard?tournamentId=2271")
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
print(data)
if error == nil {
var urlContent = NSString(data: data, encoding: NSASCIIStringEncoding) as NSString!
print(urlContent)
}
})
task.resume()
}
Looks like the right encoding here is NSASCIIStringEncodingnot NSUTF8StringEncoding.
This isn't the best way to go about this but the above answers do not work in swift 3 so I used this.
let url = NSURL(string: "http://espn.go.com/golf/leaderboard?tournamentId=2271")
if url != nil {
let task = URLSession.shared.dataTask(with: url! as URL, completionHandler: { (data, response, error) -> Void in
print(data as Any)
if error == nil {
let urlContent = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) as NSString!
print(urlContent as Any)
}
})
task.resume()
}
It should works like this :
var url = NSURL(string: "http://espn.go.com/golf/leaderboard?tournamentId=2271")
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
print(data)
if error == nil {
var urlContent = NSString(data: NSData!, encoding: Uint)
print(urlContent)
}
})
task.resume()
}
Related
I'm trying to get results from an API, and I'm having trouble running the request itself.
Here is the code I currently have:
let url = URL(string: "https://httpbin.org/get")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("data: \(dataString)")
}
}
}
task.resume()
However, it doesn't seem to run anything inside the code block in dataTask.
Thanks for your help :)
Your code works well. It seems like you're just calling the function incorrectly...try it this way:
1:
func request() {
let url = URL(string: "https://httpbin.org/get")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("data: \(dataString)")
}
}
}
task.resume()
}
2:
override func viewDidLoad() {
super.viewDidLoad()
request()
}
My application is using an NSURL like this:
var url = NSURL(string: "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=")
When I tried to make a task for getting data from this NSURL like this:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error == nil {
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
println("urlContent \(urlContent!)")
} else {
println("error mode")
}
but I got error when trying to got data from that address, although when I using safari go to link: "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=" I can see the data. How can I fix that?
Swift 2
let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encodedString = original.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLFragmentAllowedCharacterSet()),
url = NSURL(string: encodedString)
{
print(url)
}
Encoded URL is now:
"http://www.geonames.org/search.html?q=A%C3%AFn+B%C3%A9%C3%AFda+Algeria&country="
and is compatible with NSURLSession.
Swift 3
let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encoded = original.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let url = URL(string: encoded)
{
print(url)
}
Im trying to get html data from shoutoutStream , actually currently playing title...
I'm new at swift programming so i really need a help.
This is what i've tryied but still getting error:
ICY 404 Resource Not Found
icy-notice1:SHOUTcast Distributed Network Audio Server/Linux v1.9.8
icy-notice2:The resource requested was not found
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: NSURL(string: "http://s5.voscast.com:8220/7.html")!)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
var usedEncoding = NSASCIIStringEncoding
print(usedEncoding)// Some fallback value
if let encodingName = response?.textEncodingName {
let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
if encoding != UInt(kCFStringEncodingInvalidId) {
usedEncoding = encoding
}
}
if let myString = String(data: data!, encoding: usedEncoding) {
print("this is my string: \(myString)")
} else {
print("failed to decode data")
}
})
task.resume()
Please help me , i'm sooo frustrated already.
I'm following an iOS Swift guide on Udemy and this is the first issue I cannot work around:
I am supposed to see html etc printed to the console but instead I get null.
This is the section:
let url = NSURL(string: "https://google.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
(data, response, error) in
if error == nil {
var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(urlContent)
}
}
task.resume()
If I print just the data then it gives me some content back but when its encoded its nil.
Any help? Cannot move onto the next part until this is resolved.
The problem there as already mentioned by rmaddy it is the encoding you are using. You need to use NSASCIIStringEncoding.
if let url = URL(string: "https://www.google.com") {
URLSession.shared.dataTask(with: url) {
data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let urlContent = String(data: data, encoding: .ascii)
else { return }
print(urlContent)
}.resume()
}
Or taking a clue from Martin R you can detect the string encoding from the response:
extension String {
var textEncodingToStringEncoding: Encoding {
return Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(self as CFString)))
}
}
if let url = URL(string: "https://www.google.com") {
URLSession.shared.dataTask(with: url) {
data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let textEncoding = response?.textEncodingName,
let urlContent = String(data: data, encoding: textEncoding.textEncodingToStringEncoding)
else { return }
print(urlContent)
}.resume()
}
I have the following code:
var resultData:NSData?
task = session!.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in
if ((error) != nil) {
println("Error")
return
}
resultData = data
}
task!.resume()
However, after execution the resultData is nil. How can I get the data that's been returned by the request?
Check if your data is nil and then you can use it
Here is a Swift 3 example:
let url = NSURL(string: "https://itunes.apple.com/search?term=jack+johnson&limit=2")!
let request = NSMutableURLRequest(url: url as URL)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) { data, response, error in
if error != nil {
print("error: \(error!.localizedDescription): \(String(describing: error))")
}
else if data != nil {
if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
print("Received data:\n\(str)")
}
else {
print("unable to convert data to text")
}
}
}
task.resume()
the dataTask will execute the function is an async, if you want to use the result data it has to be used inside the data task function. now the print statement will print the response. If you use resultData outside the dataTask func it will return nil
var resultData:NSData?
let dataTask = session.dataTask(with: request as URLRequest) {
(data, response, error) in
guard let data = data, error == nil else { return }
if error != nil {
error
}
resultData = data
print(NSString(data: data, encoding: String.Encoding.utf8.rawValue)!)
}dataTask.resume()