Having trouble with a json-xcode/swift - json

I am trying to add values from what
was printed in the json shown by my code
to specific arrays. For example I want
the lat / lng /name from the JSon file and
add it to an array. How would I go about doing this
? I am new to swift and would appreciate the help.
My Json code is in the comments! Thanks
func getBurritosInArea() {
let keyword:String = "burrito"
let urlString =
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=\(latitude),\(longitude)&&fields=formatted_address,name,rating&radius=1500&type=restaurant&keyword=(\apikey)"
guard let request = URL(string:urlString) else { return }
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil,
let json = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers),
let results = json as? [String: Any] else { //error handling
return
}
if let placeResults = results["results"] as? [[String: Any]]{
for placeResult in results{
print(placeResult)
}
}
}
}
}
json code:
viewport = {
northeast = {
lat = "40.74642527989272";
lng = "-73.97449797010727"; };
southwest = {
lat = "40.74372562010728";
lng = "-73.97719762989271"; };
};
};
icon = "maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png"; id = c884c332c5cc1578d0c1d4d7f4d4ad451358c9e6;
name = "Baby Bo's Cantina"; "opening_hours" = { "open_now" = 1; };

Hi Please try below code,
First Create an Array Named aryDict,
func getBurritosInArea()
{
guard let url = URL(string: "your url") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: []) as? NSArray
// print(jsonResponse?.value(forKey: STR_NAME) as Any )
let array = NSArray.init(array: jsonResponse ?? [])
var aryDict = NSMutableArray.init(array: array)
// self.tblView.reloadData()
print(aryDict)
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}

Related

data from coredata is not showing on tableview in swift4

I am fetching json data and saving it in coredata. and calling it in "didFinishLaunchingWithOptions". And when i am fetching the data in "viewDidLoad", the problem is At the first time the tableview is empty. and when i am reopening the app after closing it then the data is showing in tableView. Please see my programme
func fetchTopStories(){
let moc = coreData.persistentContainer.viewContext
let myUrlString = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
guard let newsUrl = URL(string: myUrlString) else { return }
URLSession.shared.dataTask(with: newsUrl) { (data, responce, err) in
if err != nil{
print("err in fetching data")
return
}
else {
guard let myData = data else{return}
guard let jsonResult = try! JSONSerialization.jsonObject(with: myData, options: .mutableContainers) as? [Int] else{return}
for i in 0..<jsonResult.count {
let myString = "https://hacker-news.firebaseio.com/v0/item/\(jsonResult[i]).json?print=pretty"
guard let myUrl = URL(string: myString) else { return }
URLSession.shared.dataTask(with: myUrl, completionHandler: { (data, responce, err) in
if err != nil{
print("err in fetching data")
return
}
else {
guard let allData = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary else{return}
let news = News(context: moc)
if let newTitle = (allData!["title"]) as? String{
news.title = newTitle
}
if let newScore = (allData!["score"]) as? Int{
news.score = Int16(newScore)
}
if let newId = (allData!["id"]) as? String{
news.id = Int64(newId)!
}
if let newText = (allData!["text"]) as? String{
news.text = newText
}
if let newUrl = (allData!["url"]) as? String{
news.url = newUrl
}
}
}).resume()
}
}
}.resume()
self.coreData.saveContext()
}
You are saving the CoreData stack after the indices have been received. At this moment none of the dictionaries are received yet.
You need DispatchGroup to get notified when all stories have been received and then save the context. Before creating the data task enter the group, in the closure leave it (also in the edge cases). notify is called after the last iteration.
func fetchTopStories() {
let moc = coreData.persistentContainer.viewContext
let myUrlString = "https://hacker-news.firebaseio.com/v0/topstories.json"
guard let newsUrl = URL(string: myUrlString) else { return }
URLSession.shared.dataTask(with: newsUrl) { (data, responce, err) in
if err != nil{
print("err in fetching data", err!)
return
}
else {
let group = DispatchGroup()
guard let jsonResult = try! JSONSerialization.jsonObject(with: data!) as? [Int] else { return }
for anInt in jsonResult {
let myString = "https://hacker-news.firebaseio.com/v0/item/\(anInt).json"
guard let myUrl = URL(string: myString) else { return }
group.enter()
URLSession.shared.dataTask(with: myUrl, completionHandler: { (data, responce, err) in
if err != nil {
print("err in fetching data", err!)
group.leave()
return
}
else {
guard let allData = try? JSONSerialization.jsonObject(with: data!) as? [String:Any] else {
group.leave()
return
}
var news = News(context: moc)
if let newTitle = (allData!["title"]) as? String{
news.title = newTitle
}
if let newScore = (allData!["score"]) as? Int{
news.score = Int16(newScore)
}
if let newId = (allData!["id"]) as? String{
news.id = Int64(newId)!
}
if let newText = (allData!["text"]) as? String{
news.text = newText
}
if let newUrl = (allData!["url"]) as? String{
news.url = newUrl
}
group.leave()
}
}).resume()
}
group.notify(queue: DispatchQueue.main) {
self.coreData.saveContext()
}
}
}.resume()
}
A few notes:
Don't pretty-print if you are not going to print anything, the deserializer doesn't care about prettiness.
Never ever use .mutableContainers in Swift. This option is completely pointless particularly you don't mutate anything and assign the result to an immutable constant.
Don't use Foundation collection types NSArray / NSDictionary in Swift. Use native types.
Never use ugly index-based for loops in Swift to iterate arrays. Use always Fast Enumeration, there is also a for (index, element) in { ... } syntax if the index is really needed.
Print any error rather than an actually meaningless literal string "err in fetching data".
guard let myData = data else{return} is redundant. If error is nil, data is not nil and vice versa.

calling a function from a function doesn't return value unless the main function is completed swift

Guys I need assistance on swift 4.0
i have a simple function that calls a json and fills those vars with values.
self.getDataFromServer()
after 'self.getDataFromServer()' this will fill in the arrays with retrieved data. This was working great on the previous version of swift (swift 3).
This is the code after the self.getDataFromServer() and getting index out of range, because data isn't populated (PS: This was working on swift 3.0)
var totalAmount = [String]()
var remainingAmount = [String]()
self.getDataFromServer()
let newTotal = Int(totalAmount[0])! + Int(remainingAmount[0])!
let newRemaining = String(newTotal)
updateDailyData(newRemainingAmount: newRemaining, id: userID[0])
I'm getting error on 'newTotal' saying index out of range. Please Help.
I noticed that on swift 4, I'm facing this issue whenever i'm calling JSON.
The JSON Function is as below:
func getDataFromServer() {
let dateOfToday = Date()
let strDateOfToday = convertToString(myDate: dateOfToday)
let postString = "ANYTHING HERE";
let myUrl = URL(string: "ANYTHING HERE")
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.httpBody = postString.data(using: String.Encoding.utf8);
//Start the task
let task = URLSession.shared.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
let values = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
let success = ((values.value(forKey: "success") as? [String])! as NSArray) as! [String]
if (success[0] == "1")
{
self.totalAmount = ((values.value(forKey: "totalAmount") as? [String])! as NSArray) as! [String]
self.remainingAmount = ((values.value(forKey: "remainingAmount") as? [String])! as NSArray) as! [String]
}
}
//Let's convert response sent from a server side script to a NSDictionary object:
task.resume()
}
Here is your perfect working solution using Closure
Swift 4
self.getDataFromServer { (arrTotalAmount, arrRemainingAmount) in
if arrTotalAmount.count > 0, arrRemainingAmount.count > 0 {
// Your code here
let newTotal = Int(totalAmount[0])! + Int(remainingAmount[0])!
let newRemaining = String(newTotal)
updateDailyData(newRemainingAmount: newRemaining, id: userID[0])
}
}
func getDataFromServer(completion: #escaping (_ arrTotalAmount: [String], _ arrRemainingAmount: [String]) -> Void) {
let dateOfToday = Date()
let strDateOfToday = convertToString(myDate: dateOfToday)
let postString = "ANYTHING HERE";
let myUrl = URL(string: "ANYTHING HERE")
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.httpBody = postString.data(using: String.Encoding.utf8);
//Start the task
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
let values = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
let success = ((values.value(forKey: "success") as? [String])! as NSArray) as! [String]
if (success[0] == "1")
{
let totalAmount = ((values.value(forKey: "totalAmount") as? [String])! as NSArray) as! [String]
let remaininAmount = ((values.value(forKey: "remainingAmount") as? [String])! as NSArray) as! [String]
completion(totalAmount, remaininAmount)
}
}
//Let's convert response sent from a server side script to a NSDictionary object:
task.resume()
}
I can't really imagine this working in Swift 3, since the effects of your getDataFromServer function are asynchronous. More precisely, the function returns before the code inside the dataTask is executed.
Try something like this to execute code on the caller side after the dataTask has succeeded:
func getDataFromServer(onDone: () -> Void) {
...
let task = URLSession.shared.dataTask(with: request) { ... in
...
onDone()
}
task.resume()
}
And to call it:
var totalAmount = [String]()
var remainingAmount = [String]()
self.getDataFromServer {
let newTotal = Int(totalAmount[0])! + Int(remainingAmount[0])!
let newRemaining = String(newTotal)
updateDailyData(newRemainingAmount: newRemaining, id: userID[0])
}

response Data is nil

I am getting response data nil.
func fetchSinglePageData() {
var response: NSData?
var errors: NSError?
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
response = NSData(contentsOfFile:"url...?project_id=(self.projectID)&project_page=Request", options: NSDataReadingOptions(0), error: &errors)
print("LatestURL Single page:(response)")
if response == nil {
var alertview = UIAlertView(title: "Network Error", message: "Data not received due to network connection.Try again...", delegate: self, cancelButtonTitle: "Ok")
alertview.show()
}
else{
let jsonDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(response!, options: nil, error: &errors) as NSDictionary
print("JSON Response Single page:(jsonDict)")
var statuses = [NSObject : AnyObject]()
self.lblstartTime?.text = jsonDict["start_time"] as? String
self.lblcurrentStage?.text = jsonDict["current_stage"] as? String
self.lblcompletionTime?.text = jsonDict["completion_time"] as? String
self.lblManager?.text = jsonDict["manager"] as? String
}
})
}
project_id is string which is recevied from presvious page which is correctly working.
In swift 3
//make a url request
let urlString = "your_url"
let urlRequest = URLRequest.init(url: URL.init(string: urlString)!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 50)
//create a session
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, urlResponse, error) in
if error != nil{
//handle error
return
}else{
if let responseData = data{
let jsonDict = try JSONSerialization.jsonObject(with: responseData, options: [])as? [String:Any]
//handle your response here
}
}
}
task.resume()
In swift 2.2
let urlString = "your_url"
let request = NSURLRequest(URL: NSURL(string: urlString)!, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 50)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error != nil{
//handel error
print(error!.localizedDescription)
return
}
if let responseData = data{
do{
if let jsonDict = try NSJSONSerialization.JSONObjectWithData(responseData, options: [])as? [String:Any]{
//you have data in json dict
}
}catch{
print("error in parsing response")
return
}
}
}
task.resume()
func singlePageData(){
var errors: NSError?
let urlString = "xyz.com"
print("URL RESPONSE \(urlString)")
let request = NSURLRequest(URL: NSURL(string: urlString), cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 50)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error != nil{
//handel error
print(error!.localizedDescription)
var alertview = UIAlertView(title: "Network Error", message: "Data not received due to network connection.Try again...", delegate: self, cancelButtonTitle: "Ok")
alertview.show()
return
}
if let responseData = data{
var jsonDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: &errors) as NSDictionary!
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
println("Json dict value \(jsonDict)")
self.lblprojectName?.text = jsonDict["name"] as? String
println("lblprojectName: \(self.lblprojectName?.text)")
self.lblstartTime?.text = jsonDict["start_time"] as? String
println("lblstartTime : \(self.lblstartTime?.text)")
self.lblcurrentStage?.text = jsonDict["current_stage"] as? String
println("lblcurrentStage : \(self.lblcurrentStage?.text)")
self.lblcompletionTime?.text = jsonDict["completion_time"] as? String
println("lblcompletionTime : \(self.lblcompletionTime?.text)")
self.lblManager?.text = jsonDict["manager"] as? String
})
}
}
task.resume()
}
This is my answer as per Jitendra Solanki answer i have made changes to code and it is now working in Swift 1.2
After a quick look, maybe \ missing:
NSData(contentsOfFile:"url...?project_id=\(self.projectID)&project_page=Request"
In this line:
response = NSData(contentsOfFile:"url...?project_id=(self.projectID)&project_page=Request", options: NSDataReadingOptions(0), error: &errors)
you have project_id=(self.projectID), to use interpolation you should instead have project_id=\(self.projectID)
I would suggest that you separate the code to generate your full URL, then print the URL to the console and ensure that it is what you would expect.
Then you can visit the url yourself and check to see what the server returns, then once you know you have the correct URL and response you can then work to deserialise the response
EDIT: updated with URLSession (Swift 3 version)
let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
var dataTask: URLSessionDataTask?
let projectID = 12
let url = URL(string: "http://phpyouth.com/clients/halfpricedgrannyflats/app/app_response.php?project_id=\(projectID)&project_page=Request")
dataTask = defaultSession.dataTask(with: url!) {
data, response, error in
if let error = error {
print(error.localizedDescription)
} else if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
if let responseData = data {
if let json = try? JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String:AnyObject] {
print(json)
}
}
}
}
}
dataTask?.resume()

Rest API JSON request in Swift 2

I'm trying to make an application using Opendata.
This is my JSON data: http://datatank.stad.gent/4/infrastructuur/publieksanitair
The problem I have is that I don't know how to parse this JSON file.
I'm always getting "Data does not contain a root object."
So it goes wrong in the Service.swift file. I'm sure my request works because when debugging I see data is returned, but I don't know how to handle it.
You can pull my project from: https://github.com/StijnPil/iOSProjectShared/tree/develop
but I've also put the important code below:
Service.swift
import Foundation
class Service
{
enum Error: ErrorType
{
case InvalidJsonData(message: String?)
case MissingJsonProperty(name: String)
case MissingResponseData
case NetworkError(message: String?)
case UnexpectedStatusCode(code: Int)
}
static let sharedService = Service()
private let url: NSURL
private let session: NSURLSession
private init() {
let path = NSBundle.mainBundle().pathForResource("Properties", ofType: "plist")!
let properties = NSDictionary(contentsOfFile: path)!
url = NSURL(string: properties["baseUrl"] as! String)!
session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
}
func createFetchTask(completionHandler: Result<[PubliekSanitair]> -> Void) -> NSURLSessionTask {
return session.dataTaskWithURL(url) {
data, response, error in
let completionHandler: Result<[PubliekSanitair]> -> Void = {
result in
dispatch_async(dispatch_get_main_queue()) {
completionHandler(result)
}
}
guard let response = response as? NSHTTPURLResponse else {
completionHandler(.Failure(.NetworkError(message: error?.description)))
return
}
guard response.statusCode == 200 else {
completionHandler(.Failure(.UnexpectedStatusCode(code: response.statusCode)))
return
}
guard let data = data else {
completionHandler(.Failure(.MissingResponseData))
return
}
do {
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [NSDictionary] else {
completionHandler(.Failure(.InvalidJsonData(message: "Data does not contain a root object.")))
return
}
//old code
//let lots = try json.filter { $0["city"]?["name"] as? String == "Gent" }.map { try ParkingLot(json: $0) }
//new code
let lots = try json.map{ try PubliekSanitair(json: $0)}
completionHandler(.Success(lots))
} catch let error as Error {
completionHandler(.Failure(error))
} catch let error as NSError {
completionHandler(.Failure(.InvalidJsonData(message: error.description)))
}
}
}
}
Result.swift
enum Result<T>
{
case Success(T)
case Failure(Service.Error)
}
PubliekSanitair.swift
import Foundation
class PubliekSanitair
{
let type_sanit: String
init(type_sanit: String){
self.type_sanit = type_sanit
}
}
extension PubliekSanitair
{
convenience init(json: NSDictionary) throws {
guard let document = json["Document"] as? NSDictionary else{
throw Service.Error.MissingJsonProperty(name: "Document")
}
guard let folder = document["Folder"] as? NSDictionary else{
throw Service.Error.MissingJsonProperty(name: "Folder")
}
guard let placemark = folder["Placemark"] as? NSDictionary else{
throw Service.Error.MissingJsonProperty(name: "Placemark")
}
guard let extendedData = placemark["ExtendedData"] as? NSDictionary else{
throw Service.Error.MissingJsonProperty(name: "Placemark")
}
guard let schemaData = extendedData["SchemaData"] as? NSDictionary else{
throw Service.Error.MissingJsonProperty(name: "Placemark")
}
guard let simpleData = schemaData["SimpleData"] as? NSDictionary else{
throw Service.Error.MissingJsonProperty(name: "Placemark")
}
guard let type_sanit = simpleData[0]!["#text"] as? String else{
throw Service.Error.MissingJsonProperty(name: "#text in type_sanit")
}
self.init(type_sanit: type_sanit)
}
}

How to parse JSON in Swift using NSURLSession

I am trying to parse JSON but getting this error:
type of expression is ambiguous without more context
My code is:
func jsonParser() {
let urlPath = "http://headers.jsontest.com/"
let endpoint = NSURL(string: urlPath)
let request = NSMutableURLRequest(URL:endpoint!)
let session = NSURLSession.sharedSession()
NSURLSession.sharedSession().dataTaskWithRequest(request){ (data, response, error) throws -> Void in
if error != nil {
print("Get Error")
}else{
//var error:NSError?
do {
let json:AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSDictionary
print(json)
} catch let error as NSError {
// error handling
print(error?.localizedDescription)
}
}
}
//task.resume()
}
This is working fine with out try catch in Xcode 6.4 but this is not working in Xcode 7.
Don't declare an AnyObject type for your decoded object since you want it to be an NSDictionary and you're performing a conversion to do this.
Also it's better to use zero options for NSJSONSerialization instead of random ones.
In my example I've also used a custom error type just for demonstration.
Note, if you're using a custom error type, you have to also include a generic catch to be exhaustive (in this example, with a simple downcasting to NSError).
enum JSONError: String, ErrorType {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
func jsonParser() {
let urlPath = "http://headers.jsontest.com/"
guard let endpoint = NSURL(string: urlPath) else {
print("Error creating endpoint")
return
}
let request = NSMutableURLRequest(URL:endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
print(json)
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
The same with Swift 3.0.2:
enum JSONError: String, Error {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
func jsonParser() {
let urlPath = "http://headers.jsontest.com/"
guard let endpoint = URL(string: urlPath) else {
print("Error creating endpoint")
return
}
URLSession.shared.dataTask(with: endpoint) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
print(json)
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
Apple declare here.
func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask
Fix it:
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
// Your handle response here!
}
UPDATE:
func jsonParser() {
let urlPath = "http://headers.jsontest.com/"
let endpoint = NSURL(string: urlPath)
let request = NSMutableURLRequest(URL:endpoint!)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
print(error)
}.resume()
}
RESULT:
Optional(Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x7f8873f148d0 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://headers.jsontest.com/, NSErrorFailingURLKey=http://headers.jsontest.com/, NSLocalizedDescription=The resource could not be loaded because the App >Transport Security policy requires the use of a secure connection.})
Hope this helps!
For Swift 4 Web service Call , Post Method using URLSession
func WebseviceCall(){
var request = URLRequest(url: URL(string: "YOUR_URL")!)
request.httpMethod = "POST"
let postString = "PARAMETERS"
request.httpBody = postString.data(using: .utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
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)")
}
do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
// Print out dictionary
print(convertedJsonIntoDict)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
}
Here is the simplest way to parse JSON using NSUrlSession.,
let PARAMS = "{\"params1\":\"%#\",\"Params2\":\"%#\",\"params3\":\"%#\"}"
let URL = "your url here"
on submit button write this code.,
let urlStr = String(format: "%#",URL)
let jsonString = String(format:PARAMS, params1value,params2value,params3value )
// Encode your data here
let jsonData = jsonString.data(using:.utf8)
var request = URLRequest(url: URL(string: urlStr)!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
//set your method type here
request.httpMethod = "POST"
request.httpBody = jsonData
let configuration = URLSessionConfiguration.default
// create a session here
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 \(String(describing: error))")
}
else {
do {
let fetchedDataDictionary = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(fetchedDataDictionary!)
let message = fetchedDataDictionary?["response key here"] as! String
if message == "your response string" {
print(message)
}
else {
self.dataArray = (fetchedDataDictionary?["data"] as! NSArray)
}
}
catch let error as NSError {
print(error.debugDescription)
}
}
}
task.resume()
1)Make ApiConnection class in to your project..
import Foundation
class ApiConnection: NSObject {
class func postDataWithRequest(_ dicData:NSDictionary, completionHandler:#escaping (_ response:NSDictionary?,_ status:Bool)->Void)
{
let URL=Foundation.URL(string: Constant.API_URL)
let request=NSMutableURLRequest(url: URL!)
request.httpMethod="POST"
request.addValue(Constant.kApplicationJSON, forHTTPHeaderField:Constant.kContentType)
let data=try? JSONSerialization .data(withJSONObject: dicData, options: JSONSerialization.WritingOptions.prettyPrinted)
request.httpBody=data
//let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)*5))
//dispatch_after(dispatchTime, dispatch_get_main_queue()) {
let session = URLSession.shared.dataTask(with: request as URLRequest,completionHandler: { (data, response, error) in
if error==nil
{
DispatchQueue.main.async(execute: {
let dicResponse = try? JSONSerialization .jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
completionHandler(dicResponse, error==nil)
})
}
else
{
completionHandler(nil, error==nil)
}
})
session.resume()
}
}
**********************************use this in your view controller****************
let dict : NSMutableDictionary = [:];
dict["Your key"] = "your value"
dict["Your key"] = "your value"
dict["Your key"] = "your value"
ApiConnection.postDataWithRequest(dict) { (response, status) in
if(status){
print(response);
else{
print("failed webservice call");
}
}
*************************************Swift3.0*************************************
var objDic = [String: Any]()
let dic = NSMutableDictionary()
print(dic)
objDic["action"] = ""
objDic["product_id"] = self.peroductid
// arrProduct .addObjects(from: objDic) as! Dictionary
print("\(objDic)")
Alamofire.request(Constant.Webservice_productinfo,
method: HTTPMethod.post,
parameters:objDic as? Parameters,
encoding: JSONEncoding.default,
headers: nil).responseJSON
{
(response:DataResponse<Any>) in
switch(response.result)
{
case .success(_):
if response.result.value != nil
{
let status = response2?.object(forKey: "status") as! String?
if status == "error"{}
//finding the status from response
var response2 = response.result.value as AnyObject?
self.response1 = response.result.value as! NSDictionary
let type =
(self.cartlistarray[0] as!NSDictionary)["base_image"]
cell.productname.text = (self.cartlistarray[0] as!NSDictionary)["name"] as? String
//Store the result value in swift 3.0
UserDefaults.standard.set(userDetail.value(forKey: "email") as? NSString, forKey: "email")
if(UserDefaults.standard.object(forKey:"email") == nil){}
//did select row click the data pass into another view
let ProductListViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProductListViewController") as! ProductListViewController
ProductListViewController.category_id = ((self.bannerarry[0] as? [String : String])?["cat_id"])!
//or else callin from indexpath.row
item = ((cartlistarray[indexpath.row] as? NSDictionary)?.value(forKey:"product_id") as! String?)!
extension UIAlertController{
func showErrorAlert(strMesage:NSString,VC:Any)
{
let alert = UIAlertController(title: "Demo App", message: strMesage as String, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
(VC as AnyObject).present(alert, animated: true, completion: nil)
}
}
extension UILabel{
func setLabel(strTitle:String)
{
self.backgroundColor = UIColor.clear
self.textColor = UIColor.white
self.textAlignment = NSTextAlignment.left
self.font = UIFont(name: "Avenir-Light", size: 15.0)
self.font = UIFont.italicSystemFont(ofSize: 15)
self.text=strTitle
}
}
//image in to base 64
let image = imageCamera.image
let imageData:NSData = UIImageJPEGRepresentation(image!, 1.0)!as NSData
imageconvert = imageData.base64EncodedString(options: .lineLength64Characters)
base64formate = imageconvert.trimmingCharacters(in:CharacterSet.whitespaces)
print(base64formate)
print data into profle view
let imageurl:String! = SharedManager.sharedInstance().myMutableDict.value(forKey:"profileimg") as? String ?? "123"
let url = URL(string: imageurl)
DispatchQueue.global(qos: .userInitiated).async {
let imageData:NSData = NSData(contentsOf: url!)!
// When from background thread, UI needs to be updated on main_queue
DispatchQueue.main.async {
let image = UIImage(data: imageData as Data)
self.imageview.image = image
}
}
let actionSheetController: UIAlertController = UIAlertController(title: "Magento Extension App", message:response1?.object(forKey: "message") as? String, preferredStyle: .alert)
actionSheetController.addAction(UIAlertAction(title: "Ok", style: .default , handler:{ (UIAlertAction)in
print("Ok button click")
}))
self.present(actionSheetController, animated: true, completion: nil)
}
case .failure(_):
print("error: \(response.result.error)") // original
URL request
break
}
}
**************************objc**************************************************
NSDictionary *objDic1 = #{#"mode":#"loginUser",
#"email":[result
objectForKey:#"email"],
#"password":#"",
};
// With AFNetworking
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:100];
// manager set
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:WEBSERVICE_CALL_URL parameters:objDic1 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable result) {
[SVProgressHUD dismiss];
NSLog(#"This s my response %#",result);
NSLog(#"success!");
if ([[result valueForKey:kStatus] isEqualToString:kOK])
{
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
}];
****************SDK LINK*******************************************
https://github.com/AFNetworking/AFNetworking
var userDetail = NSArray()
userDetail = self.response1.value(forKey: "userData") as! NSArray
print(userDetail)
self.tmpDic = userDetail[0] as! NSDictionary
print(self.tmpDic)
var optionsdic = NSDictionary()
optionsdic = self.tmpDic.value(forKey:"options") as! NSDictionary
print(optionsdic)
self.arrayOfKeys = optionsdic.allKeys as NSArray
print(self.arrayOfKeys)
if (self.arrayOfKeys.contains("color"))
{
print("color")
self.colorarray = optionsdic.value(forKey:"color") as! NSArray
print(self.colorarray.count)
for index in 0..<self.colorarray.count
{
var dic = NSDictionary ()
dic = self.colorarray .object(at: index) as! NSDictionary
self.colorarrayobject .add(dic)
print(dic)
}
print(self.colorarrayobject)
}
else {
var defaultarray = NSArray()
defaultarray = optionsdic.value(forKey:"default") as! NSArray
print(defaultarray)
self.element0array = defaultarray[0] as! NSArray
print(self.element0array)
self.dic = self.element0array[0] as! NSDictionary
print(dic)
self.arr5 = self.dic .value(forKey: "values") as! NSArray
print(self.arr5)
for iteams in 0..<self.arr5.count
{
var type = String()
type = ((self.arr5[iteams]as! NSDictionary)["label"]! as? String)!
self.configeresizeaarray.append(type)
}
print("default")
}
}
self.imagearray = self.array[0] as! NSArray
for items in 0..<self.imagearray.count
{
var type = String()
type = ((self.imagearray [items]as! NSDictionary)["image"]! as? String)!
self.cell0imagearray.append(type)
}
self.count = self.imagearray.count as Int
self.configurePageControl()
self.tableView.reloadData()
}
else
{
}
}
else
{
}