Post file to server - Swift - html

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!

Related

Error to parse a JSON file in Swift 3

I´m newbie in Swift and I have some problems with parsing JSON using Swift 3 code.
This is my JSON (extract):
[
{
"COD_USUARIO":"4",
"0":"4",
"USUARIO":"PIEDAD",
"1":"PIEDAD",
"CLAVE":"MU\u00d1OZ",
"2":"MU\u00d1OZ",
"ACTIVO":"1",
"3":"1",
"FECHA_ALTA":"2010-12-07 00:00:00",
"4":"2010-12-07 00:00:00",
"FECHA_BAJA":null,
"5":null,
"CIF":null,
"6":null,
"TELEFONO_CASA":"",
"7":"",
"TELEFONO_MOVIL":"",
"8":"",
"EMAIL_TRABAJO":"",
"9":"",
"EMAIL_PARTICULAR":"",
"10":"",
"COLOR":"16777215",
"11":"16777215",
"ADMINISTRADOR":"0",
"12":"0",
"COD_PERSONA":"9",
"13":"9",
"IMPRESORA_ETIQUETAS":"",
"14":"",
"IMP_JUSTIFICANTES":"",
"15":"",
"VER_SESIONES":"0",
"16":"0",
"COD_EMPRESA":"0",
"17":"0",
"FECHA_TRABAJO":null,
"18":null,
"MEMORIZAR_FECHA":"0",
"19":"0",
"AVISOS_PAGOS":"0",
"20":"0",
"AVISOS_COBROS":"0",
"21":"0",
"AVISOS_DIAS":"0",
"22":"0",
"AVISOS_CONTRATOSC":"0",
"23":"0",
"24":"0"
}
]
And this is my code (extract):
let url = URL(string : "http://192.168.0.252:6996/datos/policlinica/webservices/valida.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let paramToSend = "usu=" + user + "&pass=" + pwd
request.httpBody = paramToSend.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
guard let _:Data = data else{
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print (json) //I can see my json in console
let cod_persona = json["COD_USUARIO"]
print (cod_persona)
//error: Type 'Any' has no subscript members
} catch {
print ("error")
return
}
})
task.resume()
I have tried many examples of the internet, but I can not read a specific JSON data. For example, I would like to read the "COD_USUARIO" field and save the data in a variable, but I can not get it to work well for me.
Any advice on this theme or what am I doing wrong (sure many things)
I think your problem is that your json contains array objects, so I would call it like:
json[0]["COD_USUARIO"]
Because COD_USUARIO is in the first array of the json.

Parsing nested Json data in swift 3

I am getting unexpected values back when i am parsing my json data from my api, i may be doing something wrong here as i'm quite new to swift but i was getting correct values before when i was receiving one "key" but now i have added two i cannot seem to parse the values properly.
This is the json collected from the address my code is receiving, (sorry if its hard to read havn't worked out how to do line breaks yet in my ruby api)(as long as its functional im not too worried at the moment)
{
"ratings":{
"elements":{"Ready Position":[{"description":"Neutral Grip","values":"1,2,3,4,5"},{"description":"Back Straight (Concave ir Convex?)","values":"1,2,3,4,5"},{"description":"Body Low \u0026 Feet a little more than sholder width apart","values":"1,2,3,4,5"},{"description":"Weight on Balls of Feet","values":"1,2,3,4,5"},{"description":"Head Up","values":"1,2,3,4,5"},{"description":"Sholder Blades Close","values":"1,2,3,4,5"},{"description":"Eyes Drilled","values":"1,2,3,4,5"}],"Split Step":[{"description":"Ready Position Conforms","values":"Yes,No"},{"description":"Body Position Low","values":"1,2,3,4,5"},{"description":"Legs Loaded/Prepared","values":"1,2,3,4,5"}]}
},
"comments":{}
}
Now, My swift code looks like this
let playerAPIurl = "http://linkcoachuat.herokuapp.com/api/v1/session/element?organisation=" + userorganisation + "&group=" + urlGroupSelected + "&sport=" + usersport
print(playerAPIurl)
var request = URLRequest(url: URL(string: playerAPIurl)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil {
print("ERROR")
}
else{
do {
let json = try JSONSerialization.jsonObject(with: data!) as? [String: AnyObject]
print(json)
And this is the output im getting from this print(json)
Optional({
comments = {
};
ratings = {
};
})
I know i shouldnt be getting anything more in the comments part, but in the ratings part there should be some data?
so after recieving the json and dealing with parsing it i need to access this part of it ["ratings"]["elements"] and after that im all good
thanks in advance and please bare in mine im very new to swift
Thanks
Try the below code. The url used in below code has your JSON data. This code is printing the output correctly.
func testApi(){
let url = URL(string: "https://api.myjson.com/bins/jfccx")
let session = URLSession.shared
let request = URLRequest(url: url!)
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard let data = data, error == nil else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
print(json)
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}

Cannot disable cache for requests

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.

Trouble converting JSON to data with Swift

I am trying to learn Swift. One of my projects is to try to retrieve JSON data from an internal web service (a group of Python CGI scripts) and convert it into a Swift object. I can do this easily in Python, but I am having trouble doing this in Swift. Here is my playground code:
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let endpoint: String = "http://pathToCgiScript/cgiScript.py"
let url = NSURL(string: endpoint)
let urlrequest = NSMutableURLRequest(URL: url!)
let headers: NSDictionary = ["User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)",
"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"]
urlrequest.allHTTPHeaderFields = headers as? [String : String]
urlrequest.HTTPMethod = "POST"
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlrequest) {
(data, response, error) in
guard data != nil else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("Error calling script!")
print(error)
return
}
do {
guard let received = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as?
[String: AnyObject] else {
print("Could not get JSON from stream")
return
}
print(received)
} catch {
print("error parsing response from POST")
}
}
task.resume()
I know making a 'POST' to retrieve data may look odd, but that is how the system is set up. I keep on getting:
Could not get data from JSON
I checked the response, and the status is 200. I then checked the data's description with:
print(data?.description)
I got an unexpected result. Here is a snippet:
Optional("<0d0a5b7b 22535441 54555322 3a202244 6f6e6522 2c202242 55535922...
I used Mirror, and apparently the type is NSData. Not sure what to make of this. I have tried to encode the data with base64EncodedDataWithOptions. I have tried different NSJSONReadingOptions as well to no avail. Any ideas?
Update:
I used Wireshark to double check the code in the Playground. Not only was the call made correctly, but the data being sent back is correct as well. In fact, Wireshark sees the data as JSON. The issue is trying to turn the JSON data into a Swift object.
I figured out what was wrong. I was casting to the wrong type. This is the new code:
guard let received = try! NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? [AnyObject]
The JSON was not returning an array of dictionaries but an array of objects.

Swift2 handle data from POST

Im sending a Post message to my database with swift. But how do i handle the data from that response? My variable responseString looks like this now. I want to get each parameter and work with them.
Optional([{"id":"9","name":"hallow","strasse":"street","tel_nr":"123456789","kommentar":"comment"}])
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost/getByName.php")!)
request.HTTPMethod = "POST"
let postString = "name=hallow"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
Your php is returning an array containing a dictionary, so you'd have to access it like
if let responsedict = response.first {
print(responsedict["id"])
}// prints 9
(if you know there's going to be no other elements returned first is ok...or change how your data is sent back).
You could take it one step further and parse the response in to a model e.g.
let person = Person(id: response.first?["id"], name: response.first?["name"], etc)
print("id \(person.id)")
//id 9