HTTP Get receive JSonObjects Swift DebugDescription=Invalid value around character 0 - ios

I'm getting an issue while sending an HTTP GET command to a server to retrieve JSONObjects.
here is the command:
if let url: NSURL = NSURL(string: "http://11.22.33.44:8080/SRV/getAllUsers?owner=\(User.sharedInstance.email)") {
print("\nSending URL: \(url)")
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{
(response: NSURLResponse?, data: NSData?, error: NSError?)-> Void in
print("Response: \(response) \n")
do{
var datastring = NSString(data:data!, encoding:NSUTF8StringEncoding) as String?
print("Data: \(datastring)")
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
print("Json: \(json)")
}catch {
print("Error with Json: \(error)")
}
});
I received a HTTP 200 with all header information, but I'm trying to print NSData as String (nil) and also trying to retrieve my JSONObjects, I get the following message:
Data: nil
Error with Json: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
I'm managing the server part, the servlet which is preparing JSONObjects is doing the following:
ObjectOutputStream objOut = new ObjectOutputStream(response.getOutputStream());
JSONObject jsonObj = new JSONObject();
jsonObj.put("id","1234");
objOut.writeObject(jsonObj);
objout.flush();
jsonObj = new JSONObject();
jsonObj.put("id","5678");
objOut.writeObject(jsonObj);
objout.flush();
and a last important information, I'm able to retrieve those JSONObject from an Android application without any problem but it seems the format expected in swift for JSONObjects are not the same...
EDIT
I changed the way to send HTTP GET command by using NSURLSession but before treating the JSONObject, I'm trying at least to display data as String:
typealias Payload = [String: AnyObject]
let url = NSURL(string: "http://11.22.33.44:8080/SRV/getAllUsers?owner=\(User.sharedInstance.email)")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!) { (data, response, error) -> Void in
if(error == nil)
{
let err : NSError! = nil
print("Response \(response)")
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Data: \(dataString)")
var json: Payload!
// 1
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? Payload
print("JSon: \(json)")
} catch {
print(error)
//XCPlaygroundPage.currentPage.finishExecution()
}
}
else
{
print(error?.description)
}
}
task.resume()
I Received a HTTP 200 with the right header information, so I'm sure the servlet is successfully called, but get nil in data
Data: nil
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.}
EDIT #2
by using the following line
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error data")
return
}
print("data: \(data?.debugDescription)")
I can retrieve the following:
data: Optional("OS_dispatch_data: data[0x7fc68bc45380] = { composite, size = >1067, num_records = 5 record[0] = { from = 0, length = 404, data_object = >0x7fc68bc999d0 }, record[1] = { from = 0, length = 135, data_object = >0x7fc68be1f830 }, record[2] = { from = 0, length = 264, data_object = >0x7fc68bc99a80 }, record[3] = { from = 0, length = 133, data_object = >0x7fc68bf97c20 }, record[4] = { from = 0, length = 131, data_object = >0x7fc68bca0b40 }, }>")
means I am able to retrieve data (at least!) but I don't know how I can extract from this data my JSONObject....
SOLUTION
I finally found my problem.
server part needs to prepare JSONObject like this:
response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object
out.print(jsonObject);
out.flush();
instead of using ObjectOutPutStream.
Swift part can retrieve it like this:
let url_to_request = "http://11.22.33.44:8080/SRV/getAllUsers?owner=\(User.sharedInstance.email)"
let url:NSURL = NSURL(string: url_to_request)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.timeoutInterval = 10
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error data")
return
}
var json: AnyObject?
do
{
json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
for anItem in json as! [Dictionary<String, AnyObject>] {
let nom = anItem["nom"] as! String
let prenom = anItem["prenom"] as! String
let id = anItem["id"] as! String
print("nom: \(nom) prenom: \(prenom) id: \(id)")
}
}
catch
{
print("error Serialization")
return
}
}
task.resume()

Related

How to avoid "Error Domain=NSCocoaErrorDomain Code=3840" in Swift?

I keep getting this particular error when trying to parse a JSON response in Swift:
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
Code:
let dict = [
"phone": phone,
"firstname": "\(String(describing: firstName))",
"lastname": "\(String(describing: lastName))"
]
as [String: Any]
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {
var request = URLRequest(url: URL(string: "\(config.baseURL)employee")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
request.timeoutInterval = 30.0
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
DispatchQueue.main.async {
self.alertController.singleButtonAlertController("Error", (error?.localizedDescription)!, self, self.defaultAction)
return
}
}
guard let data_ = data else {
return
}
do {
let jsonObj = try JSONSerialization.jsonObject(with: data_, options: .mutableContainers) as? NSDictionary
guard let parseJSON = jsonObj else {
return
}
self.navigationItem.rightBarButtonItem = self.rightBarButton
let meta = parseJSON["meta"] as? [String:Any]
let status = meta!["status"] as? String
if status == "200" {
isEmployeeModified = true
self.dismiss(animated: true, completion: nil)
} else {
let info = meta!["info"] as? String
let message = meta!["message"] as? String
DispatchQueue.main.async {
self.alertController.singleButtonAlertController(info!, message!, self, self.defaultAction)
}
}
} catch let error as NSError {
print(error)
}
}
task.resume()
I have used similar codes in other parts of the project and everything checks out.
According to this Error, the response from your server is not a valid JSON
Can you use responseString instead of responseJSON like below
Alamofire.request(URL, method: requestMethod, parameters: params).responseString{ response in
print(response)
}
I was able to figure out what was wrong and I'm going to explain this here for future readers. Apparently, I was doing a GET request the wrong way, so when I intend to do a POST request, for some reason, it still sees it as a GET request and that was why I kept getting the response: Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
Below is my refactored code and it works without any hassle:
let dict = [
"phone": phone,
"firstname": firstName,
"lastname": lastName
] as [String : Any]
guard let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) else {
return
}
guard let url = URL(string: "\(config.baseURL)employee") else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData as Data
request.timeoutInterval = 10
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print("JSON Response: \(response)")
}
if error != nil {
DispatchQueue.main.async {
self.navigationItem.rightBarButtonItem = self.rightBarButton
self.alertController.singleButtonAlertController("Error", (error?.localizedDescription)!, self, self.defaultAction)
return
}
}
if let data = data {
do {
let parseJSON = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
let meta = parseJSON!["meta"] as? [String:Any]
let status = meta!["status"] as? String
if status == "200" {
isEmployeeModified = true
self.dismiss(animated: true, completion: nil)
} else {
let info = meta!["info"] as? String
let message = meta!["message"] as? String
DispatchQueue.main.async {
self.alertController.singleButtonAlertController(info!, message!, self, self.defaultAction)
}
}
} catch {
print(error)
}
}
}.resume()

JSON conversion is getting failed

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.

POST w/ JSON Body - Swift3 - fragments?

I'm simply trying to send a JSON string via a Swift3 httprequest.
Tried using a Dictionary, and an escaped string ...
func getToken(successHandler: #escaping (Any) -> Void, errorHandler: #escaping (Any) -> Void) {
var request = URLRequest(url: URL(string: "http://my-api.domain.com/getToken")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do
{
// try with Dictionary
let bodyJson: [String: String] = [
"username": "theusername"
]
let bodyJsonData = try JSONSerialization.data(withJSONObject: bodyJson, options: [])
// try with escaped String
let jsonString = "{" +
"\"username\": \"theusername\"," +
"}"
let jsonStringData = jsonString.data(using: String.Encoding.utf8)
//request.httpBody = bodyJsonData
request.httpBody = jsonStringData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print(error)
errorHandler(error)
return
}
guard let data = data else {
print("Data is empty")
errorHandler("Data is empty")
return
}
var json: Any? = nil
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
DispatchQueue.main.asyncAfter(deadline: .now()) {
successHandler(json)
}
}
catch let error as NSError {
errorHandler(error)
}
}
task.resume()
}
catch
{
errorHandler(error)
}
}
I keep getting:
Handle 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 can't find how to try allowing fragments, all of the examples/tutorials are for Swift2.x :/
Unsure what to do!
// prepare json data
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
// create post request
let endpoint: String = "https://yourAPI"
let session = URLSession.shared
let url = NSURL(string: endpoint)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
let task = session.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
print(error?.localizedDescription)
return
}
}
task.resume()
} catch {
print("bad things happened")
}

A JSON parsing error occurred, here are the details:

Code
func callAddWithPOST(Name mname:String, PhoneNo mphone:String, Email memail:String, Comment mcomments:String){
var names = [String]()
let login = ["countryId":"1"]
print("Your Result is : = \(login)")
let url = NSURL(string: "http://photokeeper.mgtcloud.co.uk/commonwebservice.asmx/getStateList")!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
do {
let auth = try NSJSONSerialization.dataWithJSONObject(login, options: .PrettyPrinted)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = auth
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let badJsonString = "This really isn't valid JSON at all"
let badJsonData = badJsonString.dataUsingEncoding(NSUTF8StringEncoding)!
do {
let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
print(parsed)
let otherParsed = try NSJSONSerialization.JSONObjectWithData(badJsonData, options: NSJSONReadingOptions.AllowFragments)
}
catch let error as NSError {
print("A JSON parsing error occurred, here are the details:\n \(error)")
}
print("Done.")
})
task.resume()
} catch {
print("Error")
}}
OUTPUT
{
d = "{\"result\":[{\"stateId\":3871,\"stateName\":\"Aberdeenshire\"},{\"stateId\":3872,\"stateName\":\"Anglesey/Sir Fon\"},{\"stateId\":3873,\"stateName\":\"Angus\"},{\"stateId\":3874,\"stateName\":\"Antrim\"},{\"stateId\":3875,\"stateName\":\"Argyll And Bute\"},{\"stateId\":3876,\"stateName\":\"Armagh\"},{\"stateId\":3877,\"stateName\":\"Ayrshire\"},{\"stateId\":3878,\"stateName\":\"Bedfordshire\"},{\"stateId\":3879,\"stateName\":\"Berkshire\"},{\"stateId\":3880,\"stateName\":\"Blaenau Gwent/Blaenau Gwent\"},{\"stateId\":3881,\"stateName\":\"Bristol\"},{\"stateId\":3882,\"stateName\":\"Buckinghamshire\"},{\"stateId\":3883,\"stateName\":\"Caerphilly/Caerffili\"},{\"stateId\":3884,\"stateName\":\"Cambridgeshire\"},{\"stateId\":3885,\"stateName\":\"Cardiff/Caerdydd\"},{\"stateId\":3886,\"stateName\":\"Cardiganshire/Ceredigion\"},{\"stateId\":3888,\"stateName\":\"Carmarthenshire/Sir Gaerfyrddin\"},{\"stateId\":3890,\"stateName\":\"Cheshire\"},{\"stateId\":3891,\"stateName\":\"Clackmannanshire\"},{\"stateId\":3893,\"stateName\":\"Conwy/Conwy\"},{\"stateId\":3895,\"stateName\":\"County Durham\"},{\"stateId\":3896,\"stateName\":\"Cumbria\"},{\"stateId\":3897,\"stateName\":\"Denbighshire/Sir Ddinbych\"},{\"stateId\":3898,\"stateName\":\"Derbyshire\"},{\"stateId\":3899,\"stateName\":\"Devon\"},{\"stateId\":3901,\"stateName\":\"Dorset\"},{\"stateId\":3902,\"stateName\":\"Down\"},{\"stateId\":3904,\"stateName\":\"Dumfries And Galloway\"},{\"stateId\":3905,\"stateName\":\"Dunbartonshire\"},{\"stateId\":3906,\"stateName\":\"Dundee\"},{\"stateId\":3907,\"stateName\":\"Durham/North Yorkshire\"},{\"stateId\":3908,\"stateName\":\"East Lothian\"},{\"stateId\":3909,\"stateName\":\"East Sussex\"},{\"stateId\":3910,\"stateName\":\"East Yorkshire\"},{\"stateId\":3911,\"stateName\":\"Edinburgh\"},{\"stateId\":3912,\"stateName\":\"Essex\"},{\"stateId\":3913,\"stateName\":\"Fermanagh\"},{\"stateId\":3914,\"stateName\":\"Fife\"},{\"stateId\":3915,\"stateName\":\"Flintshire/Sir Fflint\"},{\"stateId\":3917,\"stateName\":\"Glamorgan/Morgannwg\"},{\"stateId\":3918,\"stateName\":\"Glasgow\"},{\"stateId\":3919,\"stateName\":\"Gloucestershire\"},{\"stateId\":3920,\"stateName\":\"Gwynedd/Gwynedd\"},{\"stateId\":3921,\"stateName\":\"Hampshire\"},{\"stateId\":3922,\"stateName\":\"Herefordshire\"},{\"stateId\":3923,\"stateName\":\"Hertfordshire\"},{\"stateId\":3924,\"stateName\":\"Highland\"},{\"stateId\":3925,\"stateName\":\"Kent\"},{\"stateId\":3929,\"stateName\":\"Lanarkshire\"},{\"stateId\":3930,\"stateName\":\"Lancashire\"},{\"stateId\":3932,\"stateName\":\"Leicestershire\"},{\"stateId\":3935,\"stateName\":\"Lincolnshire\"},{\"stateId\":3936,\"stateName\":\"London\"},{\"stateId\":3937,\"stateName\":\"Londonderry\"},{\"stateId\":3940,\"stateName\":\"Manchester\"},{\"stateId\":3943,\"stateName\":\"Merthyr Tydfil/Merthyr Tydfil\"},{\"stateId\":3944,\"stateName\":\"Midlothian\"},{\"stateId\":3946,\"stateName\":\"Monmouthshire/Sir Fynwy\"},{\"stateId\":3947,\"stateName\":\"Moray\"},{\"stateId\":3948,\"stateName\":\"Neath Port Talbot\"},{\"stateId\":3949,\"stateName\":\"Newport\"},{\"stateId\":3950,\"stateName\":\"Norfolk\"},{\"stateId\":3951,\"stateName\":\"Northamptonshire\"},{\"stateId\":3952,\"stateName\":\"Northumberland\"},{\"stateId\":3953,\"stateName\":\"Nottinghamshire\"},{\"stateId\":3955,\"stateName\":\"Orkney\"},{\"stateId\":3956,\"stateName\":\"Oxfordshire\"},{\"stateId\":3957,\"stateName\":\"Pembrokeshire/Sir Benfro\"},{\"stateId\":3958,\"stateName\":\"Perth And Kinross\"},{\"stateId\":3959,\"stateName\":\"Powys/Powys\"},{\"stateId\":3960,\"stateName\":\"Renfrewshire\"},{\"stateId\":3962,\"stateName\":\"Rutland\"},{\"stateId\":3963,\"stateName\":\"Scottish Borders\"},{\"stateId\":3964,\"stateName\":\"Shetland Isles\"},{\"stateId\":3965,\"stateName\":\"Shropshire\"},{\"stateId\":3967,\"stateName\":\"Somerset\"},{\"stateId\":3968,\"stateName\":\"South Yorkshire\"},{\"stateId\":3969,\"stateName\":\"Staffordshire\"},{\"stateId\":3970,\"stateName\":\"Stirling\"},{\"stateId\":3971,\"stateName\":\"Suffolk\"},{\"stateId\":3972,\"stateName\":\"Surrey\"},{\"stateId\":3973,\"stateName\":\"Swansea\"},{\"stateId\":3975,\"stateName\":\"Torfaen\"},{\"stateId\":3976,\"stateName\":\"Tyrone\"},{\"stateId\":3977,\"stateName\":\"Warwickshire\"},{\"stateId\":3979,\"stateName\":\"West Lothian\"},{\"stateId\":3980,\"stateName\":\"West Midlands\"},{\"stateId\":3981,\"stateName\":\"West Sussex\"},{\"stateId\":3982,\"stateName\":\"West Yorkshire\"},{\"stateId\":3983,\"stateName\":\"Western Isles\"},{\"stateId\":3987,\"stateName\":\"Wiltshire\"},{\"stateId\":3988,\"stateName\":\"Worcestershire\"},{\"stateId\":3989,\"stateName\":\"Wrexham\"}],\"status\":\"success\"}";
}
A JSON parsing error occurred, here are the details:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
Done.
I AM GETTING ERROR - Invalid value around character 0. I want to get data in proper format with desired key and value, will anybody please help me to fix this issues.
Your JSON response is corrupted. Use JSONLint to verify it.
Convert it from
{\"result\":[{\"stateId\":3871,\"stateName\":\"Aberdeenshire\"}
to
{
"result": {
"stateId": 3871,
"stateName": "Aberdeenshire"
}
}
Notice the removal of the backslashes.
Looks like you are getting String in your response, so try something like this.
do {
let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject]
let responseStr = parsed["d"] as! String
let correctData = responseStr.dataUsingEncoding(NSUTF8StringEncoding)
let responseDic = try NSJSONSerialization.JSONObjectWithData(correctData, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject]
print(responseDic)
}
catch let error as NSError {
print("A JSON parsing error occurred, here are the details:\n \(error)")
}
Try this,
if let result:String = parsed["d"]! {
let result = convertStringToDictionary(text: result)
print("Converted result = \(result)")
}
//SWIFT 3
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
//SWIFT 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}

Create variables from JSON array

I'm trying hard to learn IOS development.
I have followed this guide and successfully managed to create a working quiz game. The last couple of days I have been trying to connect the game to an external database. Finally after many hours I'm able to read from MYSQL using JSON parsing.
Right now Im struggling with a way to convert the json array into a normal array.
My current hardcoded questions look like this:
let questionOne = questionTemplate("the first question?", answerOne: "a answer", answerTwo: "a second answer", answerThree: "a third aswer", answerFour: "tast possible answer", correctAnswer: 2)
Then they are added to an array
spormslaArray = [questionOne, questionTwo, questionThree, questionFour, questionFive, questionSix,questionSeven]
Then im doing some more loading of answers and questions before i add them to the GUI based on an array counter from the first to the last question.
func questionTemplate(question:String, answerOne:String, answerTwo:String, answerThree:String, answerFour:String, correctAnswer:Int) -> NSArray {
//Set the question
var quizQuestion = question
//set the answers and the right answer
var firstAnswer = answerOne
var secondAnswer = answerTwo
var thirdAnswer = answerThree
var fourthAnswer = answerFour
var rightAnswer = correctAnswer
var gjennverendeSporsmal = 1
//Add all the questions and answers to an array
let questionAnswerArray = [question, firstAnswer, secondAnswer, thirdAnswer, fourthAnswer, rightAnswer]
return questionAnswerArray
}
I now want to add questions from my database into spormslaArray.I got questions loaded into xcode using this code:
func lasteJson(){
let urlPath = "http://universellutvikling.no/utvikling/json.php"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if err != nil {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
let json = JSON(jsonResult)
let count: Int? = json["data"].array?.count
// println("found \(count!) challenges")
//Im just setting a hardcoded number, it will be based on the array when I have figured that out
var tall = 7
let ct = count
for index in 0...tall-1 {
println(json["data"][index] )
//DEtte printer ut induviduelt
/*
if let questionId = json["data"][index]["id"].string {
println(questionId)
}
if let spm1 = json["data"][index]["answerOne"].string {
println(spm1)
}
if let spm2 = json["data"][index]["answerTwo"].string {
println(spm2)
}
if let spm3 = json["data"][index]["answerThree"].string {
println(spm3)
}
if let spm4 = json["data"][index]["answerFour"].string {
println(spm4)
}
if let correctAnswer = json["data"][index]["correctAnswer"].string {
println(correctAnswer)
}
*/
}
//}
})
task.resume()
This is mostly based on this code.
If Im ignoring the fact that Im getting some breakpoints when im running the app, and that nordic characters in my database makes the ios simulator crash; This is the parsing result in the command line:
{
"correctAnswer" : "1",
"id" : "0",
"answerThree" : "aa3",
"answerFour" : "aa4",
"questionTemplate" : "sporsmal",
"answerOne" : "as1",
"answerTwo" : "aa2"
}
//////Finally here is the problem///////
I have tried for hours to make a variable from the json array, into the guestion array.
I want to do something like this:
let questionOne = json["data"][index]["answerOne"].string
and then add them to an array
let questionArray[questionOne, QuestionTwo.. etc]
I have tried for hours without any progress, so my last hope is you guys! :-)
Use this...
To post JSON or to receive JSON (Leave dictionary nil to GET)
///Use completion handler to handle recieved data
func sendJSON(params:Dictionary<String, String>?, toAdressOnServer:String, customCompletionHandler:((parsedData:AnyObject?, statusCode: Int) -> Void)?){
var request = NSMutableURLRequest(URL: NSURL(string: SERVER_NAME + toAdressOnServer)!)
var session = NSURLSession.sharedSession()
var err: NSError?
if (params == nil){
request.HTTPMethod = "GET"
}else{
request.HTTPMethod = "POST"
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params!, options: nil, error: &err)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments , error: &err)
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
customCompletionHandler?(parsedData: json, statusCode: -1)
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON: AnyObject = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
// Use keyword "success" in JSON from server to register successful transmission
let success = parseJSON["success"] as? Int
if (success == nil){
customCompletionHandler?(parsedData: json, statusCode: -2)
}else{
customCompletionHandler?(parsedData: json, statusCode: success!)
}
}
else {
// The json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
customCompletionHandler?(parsedData: json, statusCode: -1)
}
}
})
task.resume()
}
And To decode the JSON in your case the array, but it can have any form.
self.sendJSON(nil, toAdressOnServer: "ADRESS", customCompletionHandler: { (parsedData, statusCode) -> Void in
//check for valid data
if (parsedData != nil){
//Loop through results
for (var x = 0; x < parsedData!.count; x++){
///primary key of the item from the internet
let pk:Int = (parsedData![x] as NSDictionary).objectForKey("pk") as Int
let month = ((parsedData![x] as NSDictionary).objectForKey("fields") as NSDictionary).objectForKey("month")! as String
let quote = ((parsedData![x] as NSDictionary).objectForKey("fields") as NSDictionary).objectForKey("quote")! as String
let quotee = ((parsedData![x] as NSDictionary).objectForKey("fields") as NSDictionary).objectForKey("quotee")! as String
})
This is an example, use parsed data as "json" and use it with the appropriate structure. In this case the JSON was An array of some dictionary with a fields dictionary that has another dictionary with more fields. So you can have any JSON structure.
I Hope this helps!
It seems that you almost have the answer there. I think what you are missing is questionArray.append(... in your loop to build your array. You could also make things easier for yourself if you modified your JSON so that the questions were in an array rather than discrete keys and change your questionTemplate to take an array rather than discrete answers.
Working with what you have however -
func lasteJson(){
let urlPath = "http://universellutvikling.no/utvikling/json.php"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
questionsArray=[Question]()
let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
else {
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if err != nil {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
else {
let questions=jsonResult["data"] as? [[String:String]]
if (questions != nil) {
for question in questions! {
let answer1=question["answerOne"]!
let answer2=question["answerTwo"]!
let answer3=question["answerThree"]!
let answer4=question["answerFour"]!
let id=question["id"]!
let questionTemplate=question["questionTemplate"]!
let correctAnswer=question["correctAnswer"]!
let newQuestion=Question(questionTemplate, answerOne: answer1, answerTwo:answer2, answerThree: answer3, answerFour: answer4, correctAnswer: correctAnswer)
questionsArray.append(newQuestion)
}
}
}
}
})
task.resume()
}
You don't show your questionTemplate, but I am not sure why/how it returns an array. My code above assumes that there is a class Question and fills in a property questionsArray

Resources