I have got a problem in SWIFT 3, trying to disable cache for the requests, server sends updated JSON texts, but my application still shows old data. This happens only when cellular data is on, with WIFI everything works.
Please, advise how to fix that, here is my code. thanks!
let tim: String = String(Date().timeIntervalSinceReferenceDate)
let urlTim = url + "?timref=" + tim
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
var request = URLRequest(url: URL(string: urlTim)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)
request.httpMethod = "POST"
request.httpBody = post.data(using: .utf8)
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
let task = URLSession.shared.dataTask(with: request)
{
data, response, error in guard let data = data, error == nil else { print("Network Error"); err?(); return; }
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("Network 200 error"); err?(); return; }
self.jsonResponse = String(data: data, encoding: .utf8)!;
}
task.resume()
So here is my solution:
If anybody faces this situation and forgot to add cachepolicy option then one have to manually clean cache. After the code will work.
Related
So I'm trying to do a quick and dirty post request to get a token but I keep
getting this error. All I want to do for right now is print the JSON so I know I can at least test the app.
<NSHTTPURLResponse: 0x600002990600> { URL: https://development-290808.ew.r.appspot.com/token } { Status Code: 422, Headers {
"Alt-Svc" = (
"h3-29=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
);
"Content-Length" = (
172
);
"Content-Type" = (
"application/json"
);
Date = (
"Wed, 16 Dec 2020 00:10:14 GMT"
);
Server = (
"Google Frontend"
);
"x-cloud-trace-context" = (
"a71f62144e6ce9a6c7046d700a6bad7a;o=1"
);
} }
{
detail = (
{
loc = (
body,
username
);
msg = "field required";
type = "value_error.missing";
},
{
loc = (
body,
password
);
msg = "field required";
type = "value_error.missing";
}
);
}
With this code
func getToken() {
let parameters = ["username" : "Zach", "password" : "Password"]
guard let url = URL(string: "https://development-290808.ew.r.appspot.com/token") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
}
And because stack overflow doesn't like it when you post mostly code and little txt, here I am adding more text so I can post this question.
Looks like it might be an issue with the request body.. your server looks to be expecting something different. Check spelling and fields on the backend.
You are using guard statement on http body, and it does not fails, but that http body is wrong, and you are not sending any params to backend, and as error says value is missing, try without guard force unwrap it(in debug purpose) and app will crash and you will get error what is wrong that part.
I am sending login information to the server that I built using ASP.NET Core. I tested my server via PostMan and Fiddler and it returns a valid response.
Here is my post request:
var request = URLRequest(url: URL(string: "http://adincebic.com/auth/login")!)
request.httpMethod = "POST"
let postString = "email=cebic.ad#gmail.com&password=a"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: 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 = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
I tried using dictionary like ["email":"myEmail","password":"myPass"] but it did not let me do it that way.
I also tried using Alamofire but again with no luck, the server always returns 415 error in the console.
To verify that my server works I created a UWP application to test it and it worked as expected.
Here is my server response in XCode:
statusCode should be 200, but is 415
response = Optional(<NSHTTPURLResponse: 0x6080002275a0> { URL: http://adincebic.com/auth/login } { status code: 415, headers {
Connection = "keep-alive";
"Content-Length" = 0;
Date = "Thu, 08 Jun 2017 12:16:12 GMT";
Server = "nginx/1.10.1 (Ubuntu)";
} })
responseString = Optional("")
I am assuming that it may be a problem with encoding or a problem with reading data.
I wrote this post requests as described in this answer: HTTP Request in Swift with POST method
Maybe you are missing the Content-Type header, like this:
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
First off, I know, there are a lot of questions on this topic, but I still don't get it.
Inside my iOS app, I want to post a string to a file on my server. I found many ways to do that online and went with the following:
func postBookingNumber() {
var request = URLRequest(url: URL(string: "http://myServerURL.com/booking-number.txt")!)
request.httpMethod = "POST"
let postString = "date=\(Date())&booking-number=\(self.getBookingNumber())" //returns string with format: "01"
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 responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
Now, the file on the server is currently emtpy, until I post something to it. My plan was to either append the new booking number string to the file, OR downloading the file, appending the new booking number string to it and replacing the online version with the one I just edited inside my app.
Questions
Does the code above & my strategy make any sense?
How do I handle the "date=\(Date())&booking-number=\(self.getBookingNumber())" request on the server side?
Can I go with HTML or do I have to use JS? PHP?
I'm an absolute beginner when it comes to server stuff, so please be kind :)
Thanks in advance!
After reviewing and trying other questions and answers on StackOverflow I continue to have the following issue.
The app is meant to verify a user's username and password, then log them into the server on another screen provided the server authenticated that the user and password are valid.
The JSON response is meant to have a key Success and if it's a 1 then ok to log on else if 0 the user can not log on.
Worked fine with Swift 2 and I performed the recommended changes moving from Swift2 to Swift 3 and have no errors but have a strange response to the following code.
let body : String = ("username=\(tkUserName.text!)&password=\(tkPassword.text!)")
var request = NSMutableURLRequest()
request = NSMutableURLRequest(url: URL(string: "https://xxxxxxxxxxxx/LoginApp")!)
request.httpMethod = "POST"
request.httpBody = body.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request as URLRequest)
{ (data, response, error) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if response == nil
{
//advise user no internet or other
}
else
{
var success : Int?
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
success = jsonResult!.object(forKey: "success") as? Int
}
catch let error as NSError
{
//action error
}
if success == 1
{
//capture all is good and go to other page
self.performSegue(withIdentifier: "unwindThenGoToTeamPage", sender: self)
}
else
{
//THIS IS WHERE IT DROPS INTO EACH TIME AS SUCCESS WAS "0"
}
}
}.resume()
Here is the server response
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 7/02/2017 10:19:31 AM
Event time (UTC): 6/02/2017 11:19:31 PM
Event ID: 1f9ff75ee64149b0994fa4a46a6ea03b
Event sequence: 5
Event occurrence: 1
Event detail code: 0
and
<NSHTTPURLResponse: 0x7b9ea440> { URL: https://xxxxxxxxxxxxx/teambeta/LoginApp } { status code: 200, headers {
"Cache-Control" = private;
"Content-Length" = 67;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 08 Feb 2017 03:48:09 GMT";
Server = "Microsoft-IIS/7.5";
"Set-Cookie" = "ASP.NET_SessionId=ixxxxxxxxxxx; domain=xxxxx.com; path=/; HttpOnly, .ASPXAUTH=xxxxxxxxxxx; domain=xxxxx.com; expires=Fri, 10-Mar-2017 17:08:09 GMT; path=/; HttpOnly, TIsMobileDevice=True; path=/";
"X-AspNet-Version" = "4.0.30319";
"X-AspNetMvc-Version" = "5.2";
"X-Powered-By" = "ASP.NET";
} }
There is a lot more the server responded with but the issue seems to be with the URL Session I am creating. The JSON serialization is working fine but no Success key so I am not giving the server correct URL data.
And I checked that the server is still working fine for Swift2 as well as the Android and Windows versions so I know it's my code.
Try with the following code, this is working fine at my end. Pls check:
var request = URLRequest(url:url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(AUTENTICATION_KEY, forHTTPHeaderField: "AuthenticateKey")
request.httpBody = try! JSONSerialization.data(withJSONObject: json, options: [])
request.timeoutInterval = 30
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
guard data != nil else
{
print("no data found: \(error)")
return
}
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
completion(json)
}
catch let parseError
{
print(parseError)
// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Error could not parse JSON to load staff: '\(jsonStr)'")
}
})
task.resume()
Hey I'm trying to figure out this problem for quite some time so now I'm asking you guys for help.
In my Project I'm trying to send a POST request to a website with a login form to access the server.But I somehow don't manage to pass the data.
The website I'm trying to access is https://edu.sh.ch
in the Inspector of my browser I can see it needs a Post method to pass the data :
<form id="form1" name="form1" autocomplete="off" method="post" action="/uniquesigfe5a0f1f915f15b647d0b7a5306be984/uniquesig0/InternalSite/Validate.asp" onsubmit="return(SubmitForm());"></form>
here's my code:
func PostingCredentials(){
let myUrl = NSURL(string: self.manipulatedUrl)
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let form1 = "user_name=MyUsername&password=MyPassword"
request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
println("response = \(response)")
// You can print out response object
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
//
println("responseString = \(responseString)")
}
task.resume()
}
Note that self.manipulateUrl equals to the url which shows up when I log in normally and submit my credentials (https://edu.sh.ch/uniquesigfe5a0f1f915f15b647d0b7a5306be984/uniquesig0/InternalSite/Validate.asp)
The Post Function posts something but the response is always some sort of error page( I'm not getting any error in the code but the response of the server is an error)
So for the end my main question are :
whats the problem with my code
where do I have to send my POST method to,to the login page url or the validation url?
Thanks in advance
Some Problem with your webpage. Something is wrong in web coding. Then also you can try below code :
let form1 = "user_name=MyUsername&password=MyPassword"
let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "https://edu.sh.ch")!)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-type")
request.HTTPBody = form1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
var str = NSString(data: data, encoding: NSUTF8StringEncoding)
//var dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
}