I am building iOS Application using Swift.I am using XCODE version 6.3.
I want to post data to server using JSON.For that i created a dictionary for performing the following operation.
//This is my dictionary right now
var parameters = ["authenticity_token":name,"platform":"mobileApp", "email": userEmail, "password": userPassword,"remember_me":"1"]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)
I want to pass data as the format shown below.
{"authenticity_token":"token","platform":"mobileApp",
"user":{"email":"email_id", "password":"123456",
"remember_me":"1"}}
Right now parameter dictionary in the Format
[platform: mobileApp, authenticity_token: a1oj3olt5jn169LHn59ZbfbrBVUyov7sDVHlOl+2YzE=, email: su#gmail.com, remember_me: 1, password: samrat]
order of the paramater also changed.
I want to pass to my dictionary.
Or is there any possibility to add two dictionaries.
This is my code for posting data to server.I have another confusion whether it is correct or not.
func postData()
{
let name = defaults.stringForKey("secretKey")
var parameters = ["authenticity_token":name,"platform":"mobileApp", "email": userEmail, "password": userPassword,"remember_me":"1"]
println("Dic\(parameters)")
let url = NSURL(string: "http://behance.moblearn.net/users/sign_in")
var session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)
let jsonStr = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
println("Post Method reached")
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 = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
if let parseJSON = json {
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
}
I am in deep trouble.I am Beginner in swift.Help will be appreciated.
Do like this:
let innerDict = ["email": "email_id", "password": "123456", "remember_me": "1"]
let mainDict = ["authenticity_token": "token", "platform": "mobileApp", "user": innerDict]
Related
I get json output from the MVC project. You can see this output in the image below. But I cannot draw this output on the swift side. For example, I sent the value 6 to the id parameter and got the output in postman. Likewise, how can I pull this data on the swift side?
#objc func gorselCEK(){
let url = URL(string: ".../MobilService/KategoriGorsel/")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "id=\(6)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String],
let sifre = json[""] {
//Doesn't go in here
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString)")
}
}
task.resume()
}
In the postman, it is GET request and in Swift, you're trying to make a POST request.
Change request method to GET
request.httpMethod = "GET"
Update URL with QueryItems
var urlComponent = URLComponents(string:".../MobilService/KategoriGorsel/")!
url.queryItems = [
URLQueryItem(name: "id", value: "6")
]
//Request
var request = URLRequest(url: urlComponent.url)
request.httpMethod = "GET"
No need to set httpBody
I am really getting stuck on this.
I have created a JSON service, that returns data like this:
[
{
"docNameField": "Test",
"docNumField": 22832048,
"docVerField": 1,
"docDataBaseField": "Legal",
"docCheckedOutWhenField": "03/05/2020",
"whereCheckedOutField": "PC0X8J9RD"
}
]
This is Postman output.
No matter how I try, I cannot seem to be able to put together the correct combination og HTTP call, deserialization, types and so on to get a list of objects out in the end.
This func below outputs this:
JSON String: Optional("[{\"docNameField\":\"Test\",\"docNumField\":22832048,\"docVerField\":1,\"docDataBaseField\":\"Legal\",\"docCheckedOutWhenField\":\"03/05/2020\",\"whereCheckedOutField\":\"PC0X8J9RD\"}]")
func LoadLockedDocumentsByDocnum(docNum:Int32) {
let json: [String: Any] = ["action":"getCheckedOutDocuments","adminUserName":"\(APPuserName)","adminPassword":"\(APPuserPassword)","adminDomain":"\(APPuserDomain)","applicationKey":"19730905{testKey}","searchTerm":docNum]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
self.documentEntries.removeAll()
let url = URL(string: "https://{URL}//CheckOut")!
var request = URLRequest(url: url)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //Optional
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let session = URLSession.shared
let dataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if let resultat = response as! HTTPURLResponse?{
if resultat.statusCode == 200{
if error != nil {
}
else {
print(data!)
if let nydata = data{
print("JSON String: \(String(data: data!, encoding: .utf8))")
}
}
}}
}
dataTask.resume()
}
You seem to have come pretty close. To get a list of objects out, you first need to declare that object:
struct MyResponseObject: Decodable { // please give this a better name
let docNameField: String
let docNumField: Int
let docVerField: Int
let docDataBaseField: String
let docCheckedOutWhenField: Date
let whereCheckedOutField: String
}
And then use a JSONDecoder to deserialise the JSON. Instead of:
print("JSON String: \(String(data: data!, encoding: .utf8))")
write:
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
decoder.dateDecodingStrategy = .formatted(formatter)
do {
// here's your list of objects!
let listOfObjects = try decoder.decode([MyResponseObject].self, from: data!)
} catch let error {
print(error) // an error occurred, you can do something about it here
}
I want to use donation payment with my custom website.
There is a URL I should connect to and pass 2 value with the name "sku" & "device_id".
As asnwer the web gives me a value with name of "status" and a paycode with a value like this "726287618769179".
If "status" equals "READY_TOPAY" I should go to next url+paycode and
then user can fill card number and password and etc.
I use this code to connect and communicate with the web:
let DID = UIDevice.currentDevice().identifierForVendor!.UUIDString
print("Device ID is : \(DID)")
let url = NSURL (string: "https://qqqq.com/rest-api/pay-request");
let requestObj = NSURLRequest(URL: url!);
webView.loadRequest(requestObj);
let request = NSMutableURLRequest(URL: NSURL(string: "https://qqqq.com/rest-api/pay-request")!)
request.HTTPMethod = "POST"
let postString = "mypayid&device_id=\(DID)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
if (responseString?.UTF8String.) {
print("YESsssss")
}
}
task.resume()
The problem is I get the first JSON answer like this:
responseString = Optional({"error":false,"status":"READY_TO_PAY","pay_code":"4443697552108","prd_status":1})
I don't know what to do with this!
How should I tell if "status" equals "READY_TO_PAY" go to next url+paycode?
Instead of making a String from your JSON data with NSString(data: data!, encoding: NSUTF8StringEncoding), decode the JSON data to a dictionary, and access its contents by safely subscripting:
if let json = try? NSJSONSerialization.JSONObjectWithData(data!, options: []) {
if let content = json as? [String:AnyObject],
status = content["status"] as? String,
payCode = content["pay_code"] as? String {
print(status)
print(payCode)
}
}
Now you can easily compare status with "READY_TO_PAY" and take necessary actions.
I am trying to code a login system with jSon. I can receive and parse the results but when i am trying to use values i am receiving fatal errors.
My code:
var request = NSMutableURLRequest(URL: NSURL(string: "http://www.somedomain.com/api/login.php")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params:NSDictionary = ["e":"\(email)", "p":"\(passwd)"]
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, 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
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
if let parseJSON = json {
var success = parseJSON["result"] as? Int
var msg = parseJSON["msg"] as? String
println("Succes: \(success!)") // This works fine i can receive the success variable from json
if success! == 1 { // this line throws error as "fatal error: unexpectedly found nil while unwrapping an Optional value"
// Do something...
} else {
// Do something...
}
}
} else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
What's the problem with my code? I can not use the values that i received from jSon in my code. I am really confused with the "Optional" thing...
When i use values in println() everything is fine, but when i use the values in code that crashes... By the way it was working fine until today :S
This is the error:
Body: Optional({"result":1,"id":"2","name":"tt","msg":"Login successfull"})
Succes: 1
fatal error: unexpectedly found nil while unwrapping an Optional value
Thanks...
I am retrieving datas from JSON by using swift. I am new to JSON. I don't how to retrieve this nested values. My previous question is Issue raised, while retriving datas from JSON by using swift . I got clarified. This is new to me. My JSON format is below. Kindly guide me.
JSON Response formats:
{
"salutation": {
"id": 1,
"salutation": "Mr"
},
"firstName": "AAA",
"middleName": "BBB",
"lastName": "C",
"employeeId": "RD484",
"station": {
"id": 86,
"stationCode": null,
"stationName": "DDD",
"subDivision": null,
"address": null
},
"subDivsion": {
"id": 11,
"divisionCode": "11",
"divisionDesc": "EEE",
"division": null
}
}
//My Attempt:
var maindict = NSDictionary() //Global declaration
var session = NSURLSession.sharedSession()
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST" //set http method as POST
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body
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)")
self.maindict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as [String: AnyObject]
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// 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)'")
}
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 = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
self.dataFromJSON() //METHOD CALLING
}
else {
// Woa, okay 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)")
//println("AUTHENTICATION FAILED")
}
}
})
task.resume()
func dataFromJSON()
{
println("Main Dict Values: \(maindict)") //PRINTING ALL VALUES
let dataArray = maindict["firstName"] as? [String:AnyObject]
println("FirstName Values: \(dataArray)") // PRINTING NIL VALUES
}
Your data structure does not begin with an array this time, but with a Dictionary. Your structure is like is:
root Dictionary -> "salutation" -> Dictionary
root Dictionary -> "station" -> Dictionary
root Dictionary -> "subDivsion" -> Dictionary
Let's say you want to access the "id" of "salutation", then:
// Just an exemple of how to download, surely you have your own way
func getJSON(url: NSURL) {
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: url)
let task = session.dataTaskWithRequest(request){
(data, response, downloadError) -> Void in
if let error = downloadError {
println(error.localizedDescription)
} else {
var jsonError: NSError?
// cast the result as a Dictionary
if let dict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as? [String: AnyObject] {
// print the dictionary to check contents
println(dict)
if let salutationDictionary = dict["salutation"] as? [String: AnyObject] {
if let id = salutationDictionary["id"] as? Int {
println(id)
}
}
}
if jsonError != nil {
println(jsonError)
}
}
}
task.resume()
}
EDIT:
My friend, your code was a mess... I suggest to you to do some cleaning when you've got errors, it helps to debug. Anyway, here's a corrected version of your new code. Pay attention to how maindict is declared on the first line. Also, you had one unnecessary call to NSJSONSerialization, I simplified it. Note: for the sake of the example, I've included your dataFromJSON function code directly inside if let parseJSON ..., but of course it doesn't mean you have to do the same.
var maindict: [String: AnyObject]?
var session = NSURLSession.sharedSession()
//let parameters = ...
let request = NSMutableURLRequest(URL: your_url!)
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, 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 err: NSError?
maindict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &err) as? [String: AnyObject]
if err != nil {
println(err!.localizedDescription)
} else {
if let parseJSON = maindict {
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
println("Main Dict Values: \(maindict)")
let firstName = maindict!["firstName"] as? String
println("FirstName: \(firstName)")
}
else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
Please pay attention to the details and study my modifications by comparing with your attempt. My answer has been tested on my own server and it works, so you can use it as a working base.
The easiest way to do this is to use a library.
1) You can use swiftyJSON. It uses the objective C JSON parsing library.
https://github.com/SwiftyJSON/SwiftyJSON
2) If you want a library which uses a pure swift parser try JSONSwift. The readme on github shows how you can retrieve nested values from the JSON file. And integrating it in your project just requires you to import a single file. https://github.com/geekskool/JSONSwift