Don't wanna be here? Send us removal request.
Text
JSON Parser POST
let parameter = ["username":"Bhushan","password":"iosbhushan"]
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "content-Type")
guard let httpBDY = try?
JSONSerialization.data(withJSONObject: parameter, options: []) else{return}
request.httpBody = httpBDY
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let response = response{
print(response)
}
do
{
guard let data = data else {return}
let json = try
JSONSerialization.jsonObject(with: data, options: [])
print(json)
}catch let parserError{
print("Parser JSON Error")
}
}.resume()
0 notes
Text
API Links
https://jsonplaceholder.typicode.com/todos
https://jsonplaceholder.typicode.com/users
0 notes
Text
JSON Parsing GET
import UIKit
struct jsonStruct:Decodable{
let name:String
let capital:String
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tblView: UITableView!
var arrData = [jsonStruct]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tbl = tblView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
tbl.lblName.text = "Name : \(arrData[indexPath.row].name)"
tbl.lblCapital.text = "Capital : \(arrData[indexPath.row].capital)"
return tbl
}
override func viewDidLoad() {
super.viewDidLoad()
getData()
}
func getData(){
let url = URL(string: "https://restcountries.eu/rest/v2/all")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
do{
if error == nil{
self.arrData = try
JSONDecoder().decode([jsonStruct].self, from: data!)
for mainArray in self.arrData{
print(mainArray.name, ":", mainArray.capital)
DispatchQueue.main.async {
self.tblView.reloadData()
}
}
}
} catch{
print("Error in Get JSON Data")
}
}.resume()
}
*** Some api Links***
https://api.letsbuildthatapp.com/jsondecodable/courses
https://api.letsbuildthatapp.com/jsondecodable/courses_missing_fields
0 notes
Text
WebServices Using Swift
// WebServiceClass.swift
// webService
// Created by Bhushan on 24/07/18.
// Copyright © 2018 Bhushan. All rights reserved.
import UIKit
typealias completionService = (_ data: Data, _ response: URLResponse, _ error: Error?) -> Void
class WebServiceClass: NSObject {
override init() {
super.init()
}
func sendGetRequest(_ dictionary: [AnyHashable: Any], withMethod method: String, withCompletion block:@escaping completionService) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(url: URL(string: method)!)
request.httpMethod = "GET"
let dataTask = session.dataTask(with: request as URLRequest) { (data,response,error) in
if error != nil{
print(error!.localizedDescription)
if block != nil {
let tempData : Data = Data()
let tempResponse : URLResponse = URLResponse()
block(tempData, tempResponse, error)
} }
else {
if block != nil {
block(data!, response!, error)
}
}
}
dataTask.resume()
}
func sendPostRequest(_ dictionary: [AnyHashable: Any], withMethod method: String, withCompletion block: @escaping completionService) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(url: URL(string: method)!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postData: Data? = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
request.httpBody = postData
// request.httpBody = postData
let dataTask = session.dataTask(with: request as URLRequest) { (data,response,error) in
if error != nil{
print(error!.localizedDescription)
if block != nil {
let tempData : Data = Data()
let tempResponse : URLResponse = URLResponse()
block(tempData, tempResponse, error)
}
// return
}
else {
if block != nil {
block(data!, response!, error)
}
}
}
dataTask.resume()
}
***Important Links***
http://images.nuptial.me/ProfilePics/Wedding1/ProfilePicForPartner1.png http://images.nuptial.me/WedsiteImages/Wedsite1/WedsiteImageForWedding1/WedsiteImage11198175568T1530284086.jpg
http://aerialyoga_api.dedicatedresource.net/login email, password , device_type
http://aerialyoga_api.dedicatedresource.net/about-us
***To Download Image***
func downloadImage(url: URL, withImage imageView:UIImageView) {
print("Download Started")
// var actInd: UIActivityIndicatorView = UIActivityIndicatorView()
// showActivityIndicatory(imgView: imageView, and: actInd)
getDataFromUrl(url: url) { (data, response, error) in
guard error == nil else { return }
print(response.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
// actInd.stopAnimating()
imageView.image = UIImage(data: data)
}
}
}
***Hints About Post Method***
func inviteeLogin(){
if isValidated(){
showLoader(OnView: view)
let serviceHandler: ServiceHandler = ServiceHandler()
let postString = "Invitees[INVITEE_EMAIL]=\(txtEmailField.text!)&Invitees[PIN_CODE]=\(txtEnterCode.text!)"
serviceHandler.sendPostRequestWithString(postString, withMethod: "http://rest.nuptial.me/wedsite-couple/login", withCompletion:{(_ data: Data, _ response: URLResponse, _ error: Error?) -> Void in
if error == nil {
do{
let dic = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any]
if ((dic?["status"] as! Int) == 1) {
DispatchQueue.main.async(execute: {() -> Void in
self.dismissLoader()
print(dic!)
let dict = dic!["data"] as! [String:AnyObject]
NPConstants.defaults.set(dict["INVITEE_ID"], forKey: "inviteeId")
NPConstants.defaults.synchronize()
let controller = self.storyboard?.instantiateViewController(withIdentifier: "NPInviteeVC") as! NPInviteeVC
self.navigationController?.pushViewController(controller, animated: true)
})
}
else
{
DispatchQueue.main.async(execute: {() -> Void in
print(dic!)
self.dismissLoader()
})
}
}
catch{
self.dismissLoader()
print("catch block")
print("Error with Json: \(error)")
}
}
else {
DispatchQueue.main.async(execute: {() -> Void in
self.dismissLoader()
})
}
})
}
}
0 notes