I'm using API and getting json data with SwiftyJSON. I need an add token for the API. How can I do this with SwiftyJson?
My code :
let jsonData = (NSData(contentsOfURL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)! as NSData)
var readableJSON = JSON(data: jsonData, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
Normally I'm adding token with this code when I use Swift's JSON :
let url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
Are you making a post/put with this data? Thats would make sense.
I suppose you already have made the request to get the readable data "jsonData" contains that. Since you ndicate you dont have the json data already this would probably work.
var url = NSMutableURLRequest(URL: NSURL(string: "http://api.football-data.org/v1/soccerseasons/424/leagueTable")!)
url.addValue("mytokenishere", forHTTPHeaderField: "X-Auth-Token")
url.HTTPMethod = "GET"
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
if error == nil {
var readableJSON = JSON(data: data, options: .MutableContainers, error: nil)
let name = readableJSON["standings"]
url.HTTPBody = try! name.rawData()
NSURLSession.sharedSession().dataTaskWithRequest(url, completionHandler: data, response, error in {
//do something with his response from getting the data
})
} else {
print(error)
}
})
This is kind of a hacky way of doing it but I think its what you are going for
Related
I need help with combining data collected from firstVC, secondVC, and thirdVC and serializing those in the fourthVC.
This link helps with one VC but I have to send only ONE FILE of JSON DATA to the server.
How to create and send the json data to server using swift language
The other method is passing a dictionary array from firstVC, secondVC, and thirdVC to the fourthVC and from the fourthVC convert the dictionaries into JSON. But i don't know how to do that.
I used the format from the answer provided in the link above, but if you need additional info, I will gladly cooperate. Thanks!
PS. Please give me useful comments that will help in any way. I need the code and not feedbacks like doing my own research and such cause I have been stressing about this for nearly a month now.
This is the UserDefault keys
if let AC = UserDefaults.standard.value(forKey: "Acc") as? String {
labeltext.text = "\(AC)"
}
if let TY = UserDefaults.standard.value(forKey: "Taxyear") as? String {
taxtext.text = "\(TY)"
}
if let BB = UserDefaults.standard.value(forKey: "Bsb") as? String {
bsbtext.text = "\(BB)"
}
Here is my JSON code
#IBAction func save(_ sender: Any){
typealias JSONDictionary = [String:Any]
let parameters = ["BankAccountNumber": "Acc", "Tax Year": "Taxyear", "my-bsb": "Bsb"]
let url = URL(string: "https://server:port/")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
let valid = JSONSerialization.isValidJSONObject(parameters) // true
print (valid)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// 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 error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
let alertMessage = UIAlertController(title: "Saved!", message: "We have recorded your information", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title:"Okay", style: UIAlertActionStyle.default, handler: nil)
alertMessage.addAction(action)
self.present(alertMessage, animated: true, completion: nil)
}
I solved it by first storing them in a variable
var TITLE = UserDefaults.standard.value(forKey: "Title")
var GN = UserDefaults.standard.value(forKey: "GivenNames")
var LN = UserDefaults.standard.value(forKey: "LastName")
Then I placed them in a parameter and that's done. It was so obvious that I can't believe I didn't solve it sooner
#IBAction func save(_ sender: Any){
let parameters = ["Tax Year": TaxYear, "Title": TITLE, "first-name": GN, "sur-name": LN]
I am trying to get a json data from webpage and put it into my app. I have search so many things online and do not find any of them solve my problem.
The sample json is here
[{"id":"1","name":"Clean Archutecture","ISBN":"9780134494166","phone":null,"email":null,"comment":null,"last_update":"2018-03-10 22:53:29","price":"40","type":"sell"},{"id":"2","name":"Math Book","ISBN":null,"phone":null,"email":null,"comment":null,"last_update":"2018-03-10 22:53:54","price":null,"type":"want"},{"id":"3","name":"abc","ISBN":null,"phone":"hi","email":null,"comment":null,"last_update":"2018-03-11 19:58:00","price":"14.5","type":"want"},{"id":"4","name":"asd","ISBN":"1234","phone":"546","email":"dgf#asdc.com","comment":"234","last_update":"2018-03-11 19:59:57","price":"123","type":"want"}]
Swift code:
import Foundation
import UIKit
class Books: NSObject{
let urlRootPath = "http://maichongju.com/dbbs.php"
let method = "GET" //This is design for the php
func getData(type:String){
var result = NSArray()
let urlPath: String = urlRootPath+"?method=GET&size=ALL"
let url: URL = URL(string: urlPath)!
let request: NSMutableURLRequest = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest){
data,response, error in
if error != nil{
print("error:!! \(String(describing: error))")
return
}
do {
result = try JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
print(result )
}catch {
print(error)
}
//print(result)
}
task.resume()
}
}
Error message is
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around
character 0." UserInfo={NSDebugDescription=Invalid value around
character 0.}
I have double check my json data, i put it into online json view and it show perfectly fine. And I really dont know how to fix this problem
You don't need to force cast json response
do like this:
jsonResponse = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
Convert it like this as this is Array of Dictioanry objects
if let responseArray: [[String:Any]] = jsonResponse as? [[String:Any]] {
// DO HERE
}
I hope this will work for you
For safe side you https://github.com/Alamofire/Alamofire for Network request and for JSON : https://github.com/SwiftyJSON/SwiftyJSON
Update:
let urlPath: String = urlRootPath+"?method=GET&size=ALL"
i think is incorrect, In your body you have added POST but in URL you are appending method=GET
request.httpMethod = "POST"
I'm building a chat app and I understand how to receive the data back but I'm having trouble sending the data. I'm trying to take two UITextField values which are the username and the message and send the data.
Variables
#IBOutlet weak var username: UITextField!
#IBOutlet weak var textBox: UITextField!
Request To Receive
#IBAction func sendMessage(_ sender: UIButton) {
let parameters = ["user": username.text, "message": textBox.text] as! [String: String]
//create the url with NSURL
let url = NSURL(string: "http://website.com/getChatLogJSON.php")
//create the session object
let session = URLSession.shared
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//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 error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
Checkout SwiftyJSON, its a neat library for your JSON needs.
data insertion into the JSON object becomes as simple as:
json["name"] = JSON("new-name")
json[0] = JSON(1)
json["id"].int = 1234567890
json["coordinate"].double = 8766.766
json["name"].string = "Jack"
json.arrayObject = [1,2,3,4]
json.dictionaryObject = ["name":"Jack", "age":25]
Here is the github page, all instructions are there https://github.com/SwiftyJSON/SwiftyJSON
When it contains all data you need to put in, you can return the raw json in a string if you wish and send that which can be parsed
//convert the JSON to a raw String
if let rawString = json.rawString() {
//Do something you want
} else {
print("json.rawString is nil")
}
I am trying to get some data from a URL which requires me to POST a JSON request. It works in the sense that I get some data back; just not the data I expected. I then used jsontest.com to test my code:
let url = NSURL(string: "http://echo.jsontest.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
do {
let params = ["echo": "abc"] as Dictionary<String, String>
//... Just make sure that 'params' is a valid JSON object
assert(NSJSONSerialization.isValidJSONObject(params))
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
} catch {
print("Error")
}
let session = NSURLSession.sharedSession()
dataTask = session.dataTaskWithRequest(request, completionHandler: {
(data: NSData?, response: NSURLResponse?, error: NSError?) in
if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200,
let data = data {
let encodedData = NSString(data:data, encoding:NSUTF8StringEncoding)
print("encodedData = \(encodedData!)")
} else {
print("Error")
}
})
dataTask?.resume()
When I run this, I see the following output from jsontest.com:
encodedData = {"": ""}
where I expected
encodedData = {"echo": "abc"}
So, do I not understand correctly whether this is how jsontest.com works, or am I doing something wrong? (Obviously, I had similar problems using other JSON services.) Any comments are appreciated.
echo.jsontest.com doesn't work with a request body but with a request url, see www.jsontest.com/#echo for details.
Turns out #Eric D is right. I found another website to test my JSON posts on and that one worked fine. So the code is basically correct after all.
I made the following changes:
let url = NSURL(string: "http://gurujsonrpc.appspot.com/guru")
let params = [ "method" : "guru.test", "params" : [ "GB" ], "id" : 123 ] as Dictionary<String, AnyObject>
and then I get the following response:
{"jsonrpc":"2.0","id":123,"result":"Hello GB!"}
Which is exactly what was expected.
Thanks!
The correct URL is http://validate.jsontest.com
Also, I don't think you are constructing the POST request body correctly. See How are parameters sent in an HTTP POST request?
I managed to fetch json from my server but now I want to add extra security by way of http headers. This is how my code barely looks like for now:
let urlPath = "http://www.xxxxxxxx.com"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if ((error) != nil) {
println("Error")
} else {
// process json
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonResult["user"])
}
})
The headers that I want to add to this request are the following:
uid, which holds an integer value
hash, which is a string
If it helps, I have another app built in Titanium framework which uses this syntax:
xhr.setRequestHeader('uid', userid);
xhr.setRequestHeader('hash', hash);
So, am basically looking for a Swift equivalent.
You are using dataTaskWithURL while you should use dataTaskWithRequest, that takes NSMutableURLRequest object as an input. Using this object you can set HTTP headers, HTTPBody, or HTTPMethod
let urlPath = "http://www.xxxxxxxx.com"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "GET" // make it post if you want
request.addValue("application/json", forHTTPHeaderField: "Content-Type")//This is just an example, put the Content-Type that suites you
//request.addValue(userid, forHTTPHeaderField: "uid")
//request.addValue(hash, forHTTPHeaderField: "hash")
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//do anything you want
})
task.resume()
I suggest you to use Alamofire for networking
https://github.com/Alamofire/Alamofire
It is written in Swift and is every easy to use. Have a look at that page.