Swift make a http request response as array - ios

I have got this swift http request
var request = URLRequest(url: URL(string: "http://www.web.com/ajax/logreg.php")!)
request.httpMethod = "POST"
let pass = pass_text_field.text!.addingPercentEncoding(withAllowedCharacters: .queryValueAllowed)!
let postString = "app_reg_pass=\(pass)"
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!)
}
let responseString = String(data: data, encoding: .utf8)
print(responseString!)
}
task.resume()
Reponse string:
Array
(
[0] => 1
[1] => Murad
)
And my response to this code is array.But when i try to treat response as array it gives me an error.How can i turn response into array so i can do this
response[0]?

Your result is most likely coming in as a JSON object, so you need to deserialize it before you can use the results.
do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [Any]
print(jsonData[0] as! Int) // should print "1"
print(jsonData[1] as! String) // should print "Murad"
} catch {
print("An error occurred")
}

Related

Swift 4 - When sending POST request to localhost, my URLRequest sends the JSON data with the dictionary as a key

Seems like a simple error, but I cannot resolve it for some reason:
let parameters = ["user_id":usernameTF.text!, "password": passwordTF.text!]
let jsonData = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
print(parameters)
print(jsonData!)
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField:"Accept")
request.httpMethod = "POST"
debugTV.text = "\(parameters["user_id"]!)"+"\(parameters["password"]!)"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options:[])
// pass dictionary to nsdata object and set it as request body
print(request.httpBody!)
} catch let error {
print(error.localizedDescription)
}
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else {
return
}
guard let data = data else {
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
// check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
}
let responseString = String(data: data, encoding: .utf8)
print(responseString!)
}
when see the NodeJS debug window, my request body is
req.body = { '[password: "test", user_id: "test"]':'' }
how can I convert the request data into a JSON object?

Data posting server gets error in swift 3?

Here i got a token number from api like as shown here "210" and it is saving using userdefaults but when i tried to retrieve data from the userdefaults then it is returning "\"210\"" like this why it is adding slashes and quotes can anyone help me how to resolve this ?
here is the code for posting key
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(self.CustomerToken!)", forHTTPHeaderField: "Authorization")
print(self.CustomerToken!)
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 = \(responseString!)")
let status = (response as! HTTPURLResponse).statusCode
self.keyStatusCode = status
print(responseString!)
self.customerCartIdNumber = responseString!
self.customerCartIdNumber = responseString!
UserDefaults.standard.set(self.customerCartIdNumber, forKey: "CustomerLoginNumber")
print(self.customerCartIdNumber!)
print(responseString!)
here is the code for getting key
let customerId = UserDefaults.standard.string(forKey: "CustomerLoginNumber")
self.customerCartId = customerId!
print(customerId!)
here is the code for posting
func customerAddToCartItemsDownloadJsonWithURl(cartApi: String){
let url = URL(string: cartApi)
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
let cartNumber = customerCartId?.replacingOccurrences(of: "\\", with: "")
let parameters : [String: Any] = ["cartItem":
[
"quote_id": "\(customerCartId!)",
"sku": "\(itemCode!)",
"qty":"1"
]
]
print(customerCartId)
print(parameters)
print(cartNumber)
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(self.customerKeyToken!)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
}
task.resume()
}

swiftyJson returns null in nested json

I'm using this function to send post values to server:
func getFirstPageApplication(EMPTY:String,completionHandler: #escaping (_ response: String) -> ())
{
var strResponse = "null"
var request = URLRequest(url: URL(string: self.baseURL+"getFirstPageApplication")!)
request.httpMethod = "POST"
let postString = "EMAIL=\(EMPTY)"
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=\(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 = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
strResponse = responseString!
completionHandler(strResponse)
}
task.resume()
}
in my other controller I use this function to use above method:
func initialFirstView()
{
RestApiManager.sharedInstance.getFirstPageApplication(EMPTY:"-"){
response in
let json = JSON(response)
print("res: \(json["sliders"])")
}
}
I got response value but json["sliders"] returns null, I don't know!
my response value:
{"sliders":[{"id":4,"title":"\u0647\u0645\u06cc\u0634\u0647 \u0628\u0647 \u0622\u0648\u0627\u0632 \u0628\u0627 \u0627\u0633\u062a\u0627\u062f\u06a9\u062a","image":"1500801181_ostadcat_slider_1.jpg","status":1,"created_at":"2017-07-23 04:43:01","updated_at":"2017-07-23 04:43:01"},{"id":6,"title":"\u06cc\u06a9\u06cc \u0628\u0631\u0627\u06cc \u0647\u0645\u0647, \u0647\u0645\u0647 \u0628\u0631\u0627\u06cc \u06cc\u06a9\u06cc","image":"1500801699_ostadcat_slider_3.jpg","status":1,"created_at":"2017-07-23 04:51:39","updated_at":"2017-07-23 04:51:39"},{"id":7,"title":"\u062d\u0631\u0641\u0647 \u0627\u06cc \u062a\u0631\u06cc\u0646 \u0627\u067e\u0644\u06cc\u06a9\u06cc\u0634\u0646 \u0645\u0648\u0633\u06cc\u0642\u06cc","image":"1500801728_ostadcat_slider_4.jpg","status":1,"created_at":"2017-07-23 04:52:08","updated_at":"2017-07-23 04:52:08"},{"id":8,"title":"\u062a\u0648 \u0647\u0645 \u0645\u06cc \u062a\u0648\u0646\u06cc \u0645\u062b\u0644 \u0645\u0646 \u0628\u0627\u0634\u06cc!!!","image":"1500801751_ostadcat_slider_2.jpg","status":1,"created_at":"2017-07-23 04:52:31","updated_at":"2017-07-23 04:52:31"}],"tutorials":[{"id":1,"home_image":"1500806287_img_home_test_6.png","tutorial_image":"1500809220_Hot-Romanian-Inna-in-black-goggles-wallpapers.jpg","tutorial_title":"\u062e\u0648\u0627\u0646\u0646\u062f\u06af\u06cc","tutorial_description":"\u0622\u0645\u0648\u0632\u0634 \u062c\u0627\u0645\u0639 \u062e\u0648\u0627\u0646\u0646\u062f\u06af\u06cc","video":"1500810916_innaHot2.mp4","video_title":"\u062e\u0648\u0627\u0646\u0646\u062f\u06af\u06cc \u0631\u0627 \u062d\u0631\u0641\u0647 \u0627\u06cc \u06cc\u0627\u062f \u0628\u06af\u06cc\u0631\u06cc\u062f","teacher_image":"1500808975_inna-dark-hair-white-dresses-digital-art.jpg","teacher_name":"\u0627\u06cc\u0646\u0627","teacher_bio":"\u0628\u0647\u062a\u0631\u06cc\u0646 \u0627\u0632 \u0633\u0627\u0644 2009 \u062a\u0627 \u0628\u0647 \u0627\u0644\u0627\u0646","status":1,"created_at":"2017-06-29 17:31:20","updated_at":"2017-07-23 11:55:16"},{"id":2,"home_image":"1500802877_img_home_test_1.jpg","tutorial_image":"1500802877_Image.png","tutorial_title":"\u0622\u0645\u0648\u0632\u0634 \u06af\u06cc\u062a\u0627\u0631 \u0627\u0633\u0644\u0634","tutorial_description":"\u06af\u06cc\u062a\u0627\u0631 \u0627\u0633\u0644\u0634 \u0631\u0627 \u06cc\u0627\u062f \u0628\u06af\u06cc\u0631\u06cc\u062f!!!","video":"1500804433_oneRepublic.mp4","video_title":"\u0646\u0645\u0648\u0646\u0647 \u0622\u0645\u0648\u0632\u0634 \u06af\u06cc\u062a\u0627\u0631","teacher_image":"1500802882_maxresdefault.jpg","teacher_name":"\u0648\u0627\u0646 \u0631\u06cc\u067e\u0627\u0628\u0644\u06cc\u06a9","teacher_bio":"\u06af\u0631\u0648\u0647 \u0648\u0627\u0646 \u0631\u06cc\u067e\u0627\u0628\u0644\u06cc\u06a9 \u0634\u0627\u0645\u0644 5 \u0639\u0636\u0648","status":1,"created_at":"2017-06-29 17:35:09","updated_at":"2017-07-23 05:37:13"}]}
#Reinier Melian
solved:
func getFirstPageApplication(EMPTY:String,completionHandler: #escaping (_ response: AnyObject) -> ())
{
var strResponse = "null"
var request = URLRequest(url: URL(string: self.baseURL+"getFirstPageApplication")!)
request.httpMethod = "POST"
let postString = "EMAIL=\(EMPTY)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
DispatchQueue.main.async {
completionHandler({} as AnyObject)
}
} else {
if let usableData = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: usableData, options:
JSONSerialization.ReadingOptions.mutableContainers)
//print("worked")
//print(jsonResult) //this part works fine
DispatchQueue.main.async {
completionHandler(jsonResult as AnyObject)
}
} catch {
DispatchQueue.main.async {
completionHandler({} as AnyObject)
}
print("JSON Processing Failed")
}
}
}
}
task.resume()
}
Try using AnyObject instead of String in your completion handler and add JSONSerialization to serialize to json
func getFirstPageApplication(EMPTY:String,completionHandler: #escaping (_ response: AnyObject) -> ())
{
var strResponse = "null"
var request = URLRequest(url: URL(string: self.baseURL+"getFirstPageApplication")!)
request.httpMethod = "GET"
let postString = "EMAIL=\(EMPTY)"
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=\(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 = \(response)")
}
do {
let json:AnyObject? = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
print(parseJSON)
}
completionHandler(parseJSON)
}
}
task.resume()
}
Then you must be able to use this without problems
func initialFirstView()
{
RestApiManager.sharedInstance.getFirstPageApplication(EMPTY:"-"){
response in
print("res: \(response["sliders"])")
}
}
This code is not tested, so please let me know if works
Hope this helps

How to parse data from server? [duplicate]

This question already has answers here:
Correctly Parsing JSON in Swift 3
(10 answers)
Closed 5 years ago.
I am getting data like {"OTP":"5480"} in a string named responseString, How can I uset it.
My Code is.
#IBAction func signupButton() {
var request = URLRequest(url: URL(string:"http://122.166.215.8:8090/RESTMVC/validateMobileNumber")!)
request.httpMethod = "POST"
let mobileNumberString : String = self.mobileNumberTextfield.text!
let postString = ["mobileNumber":mobileNumberString]
request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
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=\(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 = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
var recived = [UInt8]()
recived.append(contentsOf: data)
print(responseString!)
DispatchQueue.main.async(execute: {
self.performSegue(withIdentifier: "OTPView", sender: nil)
});
}
task.resume()
}
and I want to change that string into Array. Or is there any way in which I can get Array directly on the place of String?
To access value of "OTP" you need to parse your response string and convert it in Json dictionary you can achive this using following code, just pass your response data in JSONSerialization.jsonObject(with: data, options: .allowFragments)
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String, Any>
if let otpValue = json["OTP"] {
print("Otp value : \(otpValue)")
}
} catch {
// Handle Exception
}
You can get otp from dictionary like below.
print(responseString["OTP"])

HTTP Send Request Parameter in Swift

i want to send request with username and password for getting authentication key from server, here is my code, i don't know how send to parameter with request, please help me for solve it.
let urlString = "http://services.84069.ir/Restful/PaymentService.svc/authenticate"
func recentProfileURL(parameter : [String:String]?) -> NSURL {
let component = NSURLComponents(string: urlString)!
var queryItem = [NSURLQueryItem]()
if let param = parameter {
for (key,value) in param {
let item = NSURLQueryItem(name: key, value: value)
queryItem.append(item)
}
}
component.queryItems = queryItem
return component.URL!
}
func fetchCode(completion completion: (ProfileResult) -> Void){
let request = NSURLRequest(URL: recentProfileURL(["UserName": self.userNameParam]))
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) in
let result = self.processUserProfileRequest(data: data, error: error)
completion(result)
})
task.resume()
}
I'm trying send username and password for getting authentication code from server how can send array of parameter instead of one parameter?
Try this I hope it would be helpful for you!!
let request = NSMutableURLRequest(URL: NSURL(string: "http://example.com/login.php")!)
request.HTTPMethod = "POST"
let postString = "Username=Yourusername&password=Yourpassword"
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 = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
try this code
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
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 = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
This should work for you:
var request = NSMutableURLRequest(URL: NSURL(string: ""http://services.84069.ir/Restful/PaymentService.svc/authenticate"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["UserName":"UserName you wish to send", "password":"Password you wish to send"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")`
}

Resources