Saving Json data in Realm in swift - json

I want to save json data in Realm in swift . But I am getting error like:
Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread'"
In this situation what to use - "GCD" or "operation"
I am adding my code here
func getDataFromServer(){
let personData = Person()
let headers = [
"user_id": "1",
"access_token": "5ae39568b47d3edf12345dc7ccddf519",
]
let request = NSMutableURLRequest(url: NSURL(string: "http://prvy.in/sme/assgnment_ios/api/user/data")! as URL)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
} else {
if let data = data {
do{
guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary else{
return
}
if let resultArray = json["data"] as? NSArray{
for allData in resultArray {
if let resultData = allData as? NSDictionary{
let regdId = resultData[REGD_ID] as? String
if let firstName = resultData[FIRST_NAME] as? String{
print(firstName)
personData.firstName = firstName
}
self.saveReamData(personData)
}
}
}catch{
print("error loading data")
}
}
}
})
dataTask.resume()
}
My save function is:
func saveReamData(_ person: Person) {
let backgroundQueue = DispatchQueue(label: ".realm", qos: .background)
backgroundQueue.async {
do {
try self.realm?.write {
self.realm?.add(person)
}
} catch {
print("error saving to realm")
}
}
}

If you created Realm instance in the main queue you can use it only on the main queue. In your code you are trying to write data to Realm in the background queue but you have created Realm instance in the main queue.
If you want to write data to Realm in the background queue use this code from Realm documentation:
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
guard let person = realm.resolve(personRef) else {
return // person was deleted
}
try! realm.write {
person.name = "Jane Doe"
}
}
}

Related

How to get particular 'json' value in swift 5?

I want the 'success' value in json object but the problem is I'm getting whole json data I want only 'success' value to print
Here is my json`
{
response = {
success = 1;
successmsg = "Successful Connection";
};
}`
Here is my code in swift 5
#IBAction func girisButtonTap(_ sender: Any) {
var txtusername: String
var txtpassword: String
txtusername = usercodeText.text!
txtpassword = passwordText.text!
let Url = String(format: "http://10.10.10.53:8080/sahambl/rest/sahamblsrv/userlogin")
guard let serviceUrl = URL(string: Url) else { return }
let parameters: [String: Any] = [
"request": [
"xusercode" : "\(txtusername)",
"xpassword": "\(txtpassword)"
]
]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
request.timeoutInterval = 20
let session = URLSession.shared
struct ResponseJSON: Codable {
let response: Response
}
struct Response: Codable {
let success: Int
let successmsg: String
}
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONDecoder().decode(ResponseJSON.self, from: data)
print(json)
let successful = json.response.success == 1
} catch {
print(error)
}
}
}.resume()
}
}
I would be grateful for any progress.
Use a model struct and Codable for parsing:
struct ResponseJSON: Codable {
let response: Response
}
struct Response: Codable {
// depending on what your JSON actually looks like, this could also be
// let success: Bool
let success: Int
let successmsg: String
}
session.dataTask(with: request) { data, response, error in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONDecoder().decode(ResponseJSON.self, from: data)
print(json)
// access the success property:
let successful = json.response.success == 1
// leave off the "== 1" if it's a Bool
} catch {
print(error)
}
}
}.resume()

i am trying to parse json with swift 4, please tell me what is wrong in it?

I am trying to parse JSON using the following method, but XCode is giving me an error where I have declared "data" .
I am new, I don't understand what is wrong. Please help me.
import UIKit
struct Contacts: Decodable {
let id: Int
let name: String
let email: String
}
class ViewController: UIViewController {
override func viewDidLoad()
{
super.viewDidLoad()
let urlString = "https://api.androidhive.info/contacts/"
guard let url = URL(string: urlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, error) in
}
guard let data = data else {return}
//let datastring = String(data: data, encoding: .utf8)
do
{
let contact = try JSONDecoder().decode([Contacts].self, from: data)
print(contact.name)
} catch let jsonErr {
print("Error deserializing json:", jsonErr)
}
}
}
Three major issues.
You are ignoring the root object which is a dictionary containing the contacts array.
The value for key id is String, not Int.
A hard rule is : Everything in double quotes is String even "12" and "false"
You have to resume the task and put the code to parse the JSON into the completion handler.
struct Root : Decodable {
let contacts : [Contact]
}
struct Contact : Decodable { // It's recommended to name this kind of struct in singular form
let id, name, email: String
}
...
override func viewDidLoad()
{
super.viewDidLoad()
let urlString = "https://api.androidhive.info/contacts/"
guard let url = URL(string: urlString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error { print(error); return }
do {
let result = try JSONDecoder().decode(Root.self, from: data!)
let contacts = result.contacts
for contact in contacts {
print(contact.name)
}
} catch {
print("Error deserializing json:", error)
}
}.resume()
}
//
// ViewController.swift
// PostMethodTest
//
// Created by HABIB UR REHMAN on 12/11/2018.
// Copyright © 2018 HABIB UR REHMAN. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
struct Resturant: Decodable {
var name: String
var deliveryCharges: String
var email: String
init(_ dictionary: [String: Any]) {
self.name = dictionary["name"] as? String ?? ""
self.deliveryCharges = dictionary["deliveryCharges"] as? String ?? ""
self.email = dictionary["email"] as? String ?? ""
}
}
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "your Link Here ") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) {(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: [])
print(jsonResponse) //Response result
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
}
Please Try this its working for me.
func getContactListsApiCalling() {
var request = URLRequest(url: URL(string: "https://api.androidhive.info/contacts/")!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
if let Data = data {
let responseJSON = try JSONSerialization.jsonObject(with: Data) as? Dictionary<String, AnyObject> ?? [:]
if let contacts = responseJSON["contacts"] as? [[String :AnyObject]] {
for contact in contacts {
let id = contact["id"] as? String ?? ""
let name = contact["name"] as? String ?? ""
let email = contact["email"] as? String ?? ""
let address = contact["address"] as? String ?? ""
let gender = contact["gender"] as? String ?? ""
print(id,name,email,address,gender)
}
}
}
} catch {
print("error")
}
})
task.resume()
}
}

How to parse JSON using swift 4

I am confusing to getting detail of fruit
{
"fruits": [
{
"id": "1",
"image": "https://cdn1.medicalnewstoday.com/content/images/headlines/271/271157/bananas.jpg",
"name": "Banana"
},
{
"id": "2",
"image": "http://soappotions.com/wp-content/uploads/2017/10/orange.jpg",
"title": "Orange"
}
]
}
Want to parse JSON using "Decodable"
struct Fruits: Decodable {
let Fruits: [fruit]
}
struct fruit: Decodable {
let id: Int?
let image: String?
let name: String?
}
let url = URL(string: "https://www.JSONData.com/fruits")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else { return }
do{
let fruits = try JSONDecoder().decode(Fruits.self, from: data)
print(Fruits)
}catch {
print("Parse Error")
}
also can you please suggest me cocoapod library for fastly download images
The issue you are facing is because your JSON is returning different data for your Fruits.
For the 1st ID it returns a String called name, but in the 2nd it returns a String called title.
In addition when parsing the JSON the ID appears to be a String and not an Int.
Thus you have two optional values from your data.
As such your Decodable Structure should look something like this:
struct Response: Decodable {
let fruits: [Fruits]
}
struct Fruits: Decodable {
let id: String
let image: String
let name: String?
let title: String?
}
Since your URL doesn't seem to be valid, I created the JSON file in my main bundle and was able to parse it correctly like so:
/// Parses The JSON
func parseJSON(){
if let path = Bundle.main.path(forResource: "fruits", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONDecoder().decode(Response.self, from: data)
let fruitsArray = jsonResult.fruits
for fruit in fruitsArray{
print("""
ID = \(fruit.id)
Image = \(fruit.image)
""")
if let validName = fruit.name{
print("Name = \(validName)")
}
if let validTitle = fruit.title{
print("Title = \(validTitle)")
}
}
} catch {
print(error)
}
}
}
Hope it helps...
// Parse Json using decodable
// First in create Structure depends on json
//
//
//
struct Countory : Decodable {
let name: String
let capital: String
let region: String
}
let url = "https://restcountries.eu/rest/v2/all"
let urlObj = URL(string: url)!
URLSession.shared.dataTask(with: urlObj) {(data, responds, Error) in
do {
var countories = try JSONDecoder().decode([Countory].self, from: data!)
for country in countories {
print("Country",country.name)
print("###################")
print("Capital",country.capital)
}
} catch {
print(" not ")
}
}.resume()
Model sample:
public struct JsonData: Codable{
let data: [Data]?
let meta: MetaValue?
let linksData: LinksValue?
private enum CodingKeys: String, CodingKey{
case data
case meta
case linksData = "links"
}
}
enum BackendError: Error {
case urlError(reason: String)
case objectSerialization(reason: String)
}
struct APIServiceRequest {
static func serviceRequest<T>(reqURLString: String,
resultStruct: T.Type,
completionHandler:#escaping ((Any?, Error?) -> ())) where T : Decodable {
guard let url = URL(string: reqURLString) else {
print("Error: cannot create URL")
let error = BackendError.urlError(reason: "Could not construct URL")
completionHandler(nil, error)
return
}
let urlRequest = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil else {
completionHandler(nil, error)
return
}
guard let responseData = data else {
print("Error: did not receive data")
let error = BackendError.objectSerialization(reason: "No data in response")
completionHandler(nil, error)
return
}
let decoder = JSONDecoder()
do {
let books = try decoder.decode(resultStruct, from: responseData)
completionHandler(books, nil)
} catch {
print("error trying to convert data to JSON")
print(error)
completionHandler(nil, error)
}
}
task.resume()
}
}
To Access:
let apiService = APIServiceRequest()
var dataArray: [String: Any]? //global var
apiService.serviceRequest(reqURLString: endPoint, resultStruct: VariantsModel.self, completionHandler: {dataArray,Error in})
POST Method
func loginWS(endpoint: String, completionHandler: #escaping (Any?) -> Swift.Void) {
guard let sourceUrl = URL(string: endpoint) else { return }
let request = NSMutableURLRequest(url: sourceUrl)
let session = URLSession.shared
request.httpMethod = "POST"
request.addValue(vehiceHeader, forHTTPHeaderField: "X-Vehicle-Type")
request.addValue(contentHeader, forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request as URLRequest) { data, response, error in
guard let data = data else { return }
do {
let responseData = try JSONDecoder().decode(JsonData.self, from: data)
print("response data:", responseData)
completionHandler(responseData)
} catch let err {
print("Err", err)
}
}.resume()
}

How do I get values from a complex JSON object?

Is it possible that someone could show me how to get the names of these pizza places printing out? My application prints out the expected "Status Code: 200". However, my console only shows empty brackets []. I suspect that I am not pulling values from my JSON object properly.
I'm using this link for my API.
Link For API
Question
How can I properly fetch values from my serialized JSON object?
relevant code:
// Response
if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200, let data = data {
print("Status Code: \(httpResponse.statusCode)")
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
if let pizzaPlaces = json["response"] as? [[String: AnyObject]] {
for place in pizzaPlaces {
if let name = place ["name"] as? String {
self.PizzaClass.append(name)
}
}
}
} catch {
print("Error Serializing JSON Data: \(error)")
}
print(self.PizzaClass)
}
}).resume()
You need to cast your NSJSONSerialization.JSONObjectWithData result as a [String:AnyObject].
let jsonObject = try NSJSONSerialization.JSONObjectWithData(returnedData, options: .MutableLeaves) as! [String: AnyObject]
Once you have that all you need to do is pay attention to what you're casting. Take the code below for an example. If we want to get our response object using jsonObject["response"] what kind of data structure do we have?
"response": {
"venues": [{
//... continues
}]
}
On the left we have "response" which is a string, on the right we have {} which is an AnyObject. So we have [String: AnyObject]. You just need to think about what object your dealing with piece by piece. Below is a working example that you can just paste into your application.
full working code:
func getJson() {
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.foursquare.com/v2/venues/search?client_id=0F5M0EYOOFYLBXUOKTFKL5JBRZQHAQF4HEM1AG5FDX5ABRME&client_secret=FCEG5DWOASDDYII4U3AAO4DQL2O3TCN3NRZBKK01GFMVB21G&v=20130815%20&ll=29.5961,-104.2243&query=burritos")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard let testResponse = response as? NSHTTPURLResponse else {
print("\(response)")
return
}
guard let status = HTTPStatusCodes(rawValue: testResponse.statusCode) else {
print("failed to unwrap status")
return
}
print(status)
switch status {
case .Created:
print("ehem")
case .BadRequest:
print("bad request")
case .Ok:
print("ok")
guard let returnedData = data else {
print("no data was returned")
break
}
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(returnedData, options: .MutableLeaves) as! [String: AnyObject]
guard let response = jsonObject["response"] as? [String: AnyObject] else { return }
guard let venues = response["venues"] as? [AnyObject] else { return }
guard let location = venues[0]["location"] as? [String:AnyObject] else { return }
guard let formattedAddress = location["formattedAddress"] else { return }
print("response: \n\n \(response)\n------")
print("venues : \n\n \(venues)\n-------")
print("location : \n\n \(location)\n------")
print("formatted address : \n \(formattedAddress)")
} catch let error {
print(error)
}
// update user interface
dispatch_sync(dispatch_get_main_queue()) {
print("update your interface on the main thread")
}
}
}
task.resume()
}
place this either in its own file our outside of the class declaration,
enum HTTPStatusCodes : Int {
case Created = 202
case Ok = 200
case BadRequest = 404
}
Not that this was what you are looking for, but since you are new to Swift take a look at Alamofire. It handles JSON serialization for you. And when you need to chain calls PromiseKit is super slick.
Alamofire.request(.GET, url).responseJSON {response in
switch (response.result) {
case .Success(let value):
let pizzas = JSON(value).arrayValue
for place in pizzaPlaces {
if let name = place ["name"] as? String {
self.PizzaClass.append(name)
}
}
case .Failure(let error):
if let data = response.data, let dataString = String(data: data, encoding: NSUTF8StringEncoding) {
print("ERROR data: \(dataString)")
}
print("ERROR: \(error)")
}
}

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
{
}