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()
}
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()
}
Here I have to post base64encoded image to server. Below is my code which I am using:
func post_request_image(api:String){
if (imageview.image == nil)
{
return
}
let image_data = UIImageJPEGRepresentation(imageview.image!, 1.0)
if(image_data == nil)
{
return
}
loader.showLoadingAlert(view: self.view, title: "")
var web_apis_3 = api
// print(web_apis_3)
var request = URLRequest(url: URL(string: web_apis_3)!)
request.httpMethod = "POST"
do {
request.httpBody =
image_data?.base64EncodedString()
} catch let error {
print(error.localizedDescription)
}
// let content = String(data: json!, encoding:
String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
}
But it is giving me this error:
cannot assign value of type String to type Data
How can I resolve this?
if the server expects a string:
let image = UIImage(named: "sample")
guard let imgData = UIImagePNGRepresentation(image) else { return }
let base64String = imgData.base64EncodedString(options: .lineLength64Characters)
then submit base64String to the server in whatever way is needed.
for me I needed to submit:
let parameters: [String: String] = [
"image": base64String
]
since youre needing data, you should be able to submit imgData
I am trying to download webcontent for a weather app that I am making. When I run the app the source code on the website does not appear on my Xcode. I also updated my info.plist to accept web content.
Do you have an idea on what the problem is and how I can solve it?
I have a copied my code below:
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "http://weather.weatherbug.com/weather-forecast/now/abuja")!
let request = NSMutableURLRequest(url:url as URL)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil{
print(error.debugDescription)
}
else {
if let unwrappedData = data{
let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
print(dataString as Any)
}
}
}
task.resume()
}
Change your url to use https and it should work.
let url = NSURL(string: "https://weather.weatherbug.com/weather-forecast/now/abuja")!
Here's an example in Swift 4 for downloading a document and parsing as JSON:
// If you're doing this in an Xcode Playground, uncomment these lines:
// import XCPlayground
// XCPSetExecutionShouldContinueIndefinitely()
let url = URL(string: "http://json-schema.org/example/geo.json")!
let task = URLSession.shared.dataTask(with: url) {
data, response, error in
guard error == nil else { return }
guard data != nil else { return }
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any] {
print(json)
}
} catch { return }
}
task.resume()
Use "if let" instead of only "let" and it should work.
if let url = URL(string:"http://weather.weatherbug.com/weather-forecast/now/abuja"){
let request = NSMutableURLRequest(url: url)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, responds, error in
if error != nil{
print(error!)
} else {
if let unwrappedData = data {
let dataString = NSString(data: unwrappedData, encoding: String.Encoding.utf8.rawValue)
print(dataString!)
DispatchQueue.main.sync(execute: {
})
}
}
}
task.resume()
}
Use
let myURLString = "http://weather.weatherbug.com/weather-forecast/now/abuja"
guard let myURL = URL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return
}
do {
let myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
print("HTML : \(myHTMLString)")
} catch let error {
print("Error: \(error)")
}
From Link
Please review my code am badly stuck on this issue.
JSON conversion is not happening & it is going into catch block & printing following error.
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
I've tried everything which is suggested here on StackOverflow but no luck.
I've trimmed my code for better understanding.
import Foundation
class Server
{
class func convertStringToDictionary(_ data: Data) -> [String:Any]?
{
do
{
let convertedDict = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
return convertedDict
}
catch let error as NSError
{
print(error)
}
return nil
}
class func registerUser( userInfo: String)
{
let url = URL(string: "http://132.148.18.11/missedprayers/welcome/register")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = "request=" + userInfo
request.httpBody = postString.data(using: .utf8)
//----------------------------------------
let task = URLSession.shared.dataTask(with: request)
{
data, response, error in
guard let data = data, error == nil
else
{
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
{
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
//--------------
let finalData = Server.convertStringToDictionary(data)
print(finalData)
}
task.resume()
}
func submitBtnTapped(_ sender: AnyObject)
{
let userInfoDict = [
"name":"Maaz Patel",
"phoneNum":"+91899885623",
"email":"maaz#gmail.com",
"city":"pune",
"country":"India",
"dobEnglish":"11-02-1992",
"app":"Dalail",
"aqeeda":"Sufi",
"gender":"male",
"MCCycle":""
]
//-------------------
do
{
let jsonData = try JSONSerialization.data(withJSONObject: userInfoDict, options: [] )
let jsonStr = String.init(data: jsonData, encoding: String.Encoding.utf8)
Server.registerUser(userInfo: jsonStr!)
}
catch let error as NSError
{
print(error)
}
}
}
Consider "SubmitBtnTapped" function is getting called from somewhere.
When am trying on Postman it's working also on Android same web service is working fine.
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()
}