Unable to add parameter to API in swift - json

I am getting parameter value from other viewcontroller, and i am getting parameter valueperfectly but which i am unable to add to API
here if i hardcode eventStatus then its working
and eventStatus value from otherviewcontroller also coming perfectly which i am unable to add to API
if i hard code like this its working
var eventType = "Draft"
let string = Constants.GLOBAL_URL + "/get/allevents/?eventstatus=\(self.eventType)"
Code: here i am getting correct eventStatus value but while breakpoint its control goes to else, why?
class EventsViewController: UIViewController {
var eventsListArray = [AnyObject]()
// var eventType = "Draft"
var eventType: String!
var eventList : EventsModel? = nil
#IBOutlet weak var eventsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getAllEventsList()
}
func getAllEventsList() {
DispatchQueue.main.async {
let headers = ["deviceid": deviceId,"userType": "personal","key": personalId]
DispatchQueue.main.async {
//let string = Constants.GLOBAL_URL + "/get/allevents/?eventstatus=\(self.eventType)"
let string = Constants.GLOBAL_URL + "/get/allevents"
var urlComponents = URLComponents(string: string)
let eventStatus = self.eventType
print("event status value in API call \(eventStatus)")
let requestEventType = URLQueryItem(name: "eventstatus", value: eventStatus)
urlComponents?.queryItems = [requestEventType]
let urlStr = urlComponents?.url
var request = URLRequest(url: urlStr!, cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers as! [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
DispatchQueue.main.async {
if error == nil {
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!) as! [String :Any]
print("publish event \(jsonObject)")
self.eventList = EventsModel.init(fromDictionary: jsonObject)
DispatchQueue.main.async {
if self.eventList?.events.count != 0 {
DispatchQueue.main.async {
self.eventsTableView.reloadData()
}
}
else {
DispatchQueue.main.async {
Constants.showAlertView(alertViewTitle: "", Message: "No Events \(self.eventType)", on: self)
self.eventList?.events.removeAll()
self.eventsTableView.reloadData()
}
}
}
} catch { print(error.localizedDescription) }
} else {
Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self)
}
}
}
})
dataTask.resume()
}
}
}
}
where i am wrong, why eventStatus value not adding to API.. please suggest me

it looks like you have a POST request and you need to use request data instead URL parameters.
HTTP Request in Swift with POST method here you can see:
let parameters: [String: Any] = [
"eventstatus": yourValue
]
request.httpBody = parameters.percentEncoded()
You also need to create parameters with eventStatus. And put it in
request.httpBody = parameters.percentEncoded()
If this endpoint on your server waits on this data in request body than you could not add it like a URL parameter.
Also, don't forget these 2 extensions from the example
extension Dictionary {
func percentEncoded() -> Data? {
return map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]#" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}

The solution must be obvious from the discussion in the comments. Although you seem a little puzzled so, I'm adding this to help you out. The value of eventType is never getting allocated to a value, it is remaining as nil unless you set it's value at a point in your code before the API call. So here is a way for you to figure this out:
let string = "https://www.google.com" + "/get/allevents"
var urlComponents = URLComponents(string: string)
let eventStatus = self.eventType ?? "Published" // here value is defaulted to "Published"
let requestEventType = URLQueryItem(name: "eventstatus", value: eventStatus)
urlComponents?.queryItems = [requestEventType]
let urlStr = urlComponents?.url
print(urlStr?.absoluteString)
Here, we're setting a default value for eventType for the scenario where eventType is nil.

Related

How to pass two values in URL body in JSON swift?

I am trying to add parameters in URL body like below
func getUserProfile() {
let deviceId: String = "HardcodeDEVICEIDforiTaag"//(UIDevice.current.identifierForVendor?.uuidString)!
let personalId: String = UserDefaults.standard.string(forKey: "USERID") ?? ""
let headers = ["deviceid": deviceId,"userType": "personal","key": personalId]
let string = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/getprofile/"
var urlComponents = URLComponents(string: string)
let requestedUserType = URLQueryItem(name: "requestedUserType", value: "personal")
let requestedItem = URLQueryItem(name: "requestedKey", value: personalId)
urlComponents?.queryItems = [requestedItem, requestedUserType]
let urlStr = urlComponents?.url
print(urlStr?.absoluteString)
let request = NSMutableURLRequest(url: NSURL(string:urlStr)! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers as! [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if error == nil {
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
self.userModel = ProfileModel.init(fromDictionary: jsonObject)
print("profile json \(jsonObject)")
print("profile personalid 2222\(personalId)")
if (self.userModel?.userId) != nil {
DispatchQueue.main.async {
self.updateUserDetails()
self.addressTableview.reloadData()
}
} else { DispatchQueue.main.async { Constants.showAlertView(alertViewTitle: "", Message: "No user data found", on: self)}}
} catch { print(error.localizedDescription) }
} else {
//Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self)
}
}
})
dataTask.resume()
}
then got error:
Cannot convert value of type 'URL?' to expected argument type 'String'
i got above error when i am trying to add url to request.
Please help me to solve this error.
This how one should create a url with different components:
let string = "http://itaag-env-1-south-1.elasticbeanstalk.com/getprofile"
var urlComponents = URLComponents(string: string)
let requestedItem = URLQueryItem(name: "requestedKey", value: "yourReqKey")
let requestedUserType = URLQueryItem(name: "requestedUserType", value: "personal")
urlComponents?.queryItems = [requestedItem, requestedUserType]
let url = urlComponents?.url
print(url?.absoluteString)
Edit: Finally use this code to get your request :-
let request = NSMutableURLRequest(url: url!, cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)

JSON Parsing sometimes crashes Swift

I am parsing JSON in my iOS app and sometimes when the network connection is weak but isn’t gone, the app will crash while trying to parse the JSON, because it says it had an error while force unwrapping a nil.
The code I use for that is here.
//
// MessageModel.swift
// truthordare
//
// Created by Dustin Palmatier on 11/2/19.
// Copyright © 2019 Hexham Network. All rights reserved.
//
import UIKit
protocol MessageModelProtocol: class {
func itemsDownloaded(items: NSArray)
}
class MessageModel: NSObject, URLSessionDataDelegate {
//properties
weak var delegate: MessageModelProtocol!
let urlPath = "Redacted" //this will be changed to the path where service.php lives
let deleteUrl = "REDACTED"
func downloadItems(TYPE: String, IDENTIFIER: String) {
let url: URL = URL(string: urlPath)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = "type=\(TYPE)&identifier=\(IDENTIFIER)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON(data!)
}
}
task.resume()
}
func deleteItems(TYPE: String, SKU: String) {
let myUrl = URL(string: "https://truthordare.hexhamnetwork.com/api/92fFDd93D/erase.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "type=\(TYPE)&sku=\(SKU)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error ?? "Empty" as! Error)")
return
}
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options: [.allowFragments, .mutableContainers]) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let tables = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let table = TableModel()
//the following insures none of the JsonElement values are nil through optional binding
if let sku = jsonElement["SKU"] as? String,
let message = jsonElement["MESSAGE"] as? String
{
table.sku = sku
table.message = message
}
tables.add(table)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(items: tables)
})
}
}
It crashes once it gets to
self.delegate.itemsDownloaded(items: tables)
It says that it received a nil while force unwrapping
To initialize the delegate I called this within the classes that were calling this.
messageModel.delegate = self
To avoid the crash reliably declare delegate as regular optional
weak var delegate: MessageModelProtocol?
and call it
self.delegate?.itemsDownloaded(items: tables)
In Swift 4+ it's highly recommended to use the Codable protocol and in any Swift version a completion handler rather than protocol / delegate.
And don't use NS... collection types in Swift at all. Use native types. And .mutableContainers / .allowFragments is pointless in Swift if the expected type is a collection type. Omit the parameter.

Parsed JSON not updating on api call for a long time

For some reason the JSON object from parsing doesnt update after network calls to and api we built. I check the endpoint and now for a fact it updates right away. I have a timer being called every 10 sec to make the call but the parsed json doesnt update until after a minute or so. I have tried putting it on the main thread and that still doesnt work. Here is my code:
#objc func getLaunches() {
let simulator = UserDefaults.standard.string(forKey: self.launchSimulator)
if(simulator == self.password){
print("they are the same")
}
guard let launchUrl = URL(string: launchesURL) else {
return
}
let request = URLRequest(url: launchUrl)
DispatchQueue.main.async { [weak self] in
let task = URLSession.shared.dataTask(with: request, completionHandler: {
(data, response, error) -> Void in
if let error = error {
print(error)
return
}
// Parse JSON data
if let data = data {
self?.launches.removeAll()
self?.launches = (self!.parseJsonData(data: data))
let nextlaunch = self?.launches[0]
// Reload table view
self?.hours = nextlaunch?.time
self?.yearMonth = nextlaunch?.date
var fulltime = self?.yearMonth
fulltime!.insert("-", at: fulltime!.index(fulltime!.startIndex, offsetBy: 4))
fulltime!.insert("-", at: fulltime!.index(fulltime!.startIndex, offsetBy: 7))
fulltime = fulltime! + " "
fulltime = fulltime! + self!.hours
let fullFormatter = DateFormatter()
fullFormatter.dateFormat = "YYYY-MM-dd HH:mm"
fullFormatter.timeZone = TimeZone(abbreviation: "EST")
self?.launchDate = fullFormatter.date(from: fulltime!)
self?.getCountdown()
}
})
task.resume()
}
}
//parse launch info from json to dictionary into launches object
func parseJsonData(data: Data) -> [NextLaunch] {
var launches = [NextLaunch]()
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options:
JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary
let jsonLaunches = jsonResult?["launches"] as! [NSDictionary]
for jsonLaunch in jsonLaunches {
let launch = NextLaunch()
launch.date = jsonLaunch["date"] as! String
launch.time = jsonLaunch["time"] as! String
if(launch.time == ""){
launch.time = "00:00"
}
launch.mission = jsonLaunch["mission"] as! String
launch.launchpad = jsonLaunch["launch_pad"] as! String
launch.image = jsonLaunch["image"] as! String
launch.delay = jsonLaunch["delayed"] as! String
//show delay image if it is delayed
if(launch.delay == "1"){
self.delayed()
}else{
self.notDelayed()
}
launches.append(launch)
}
} catch {
print(error)
}
return launches
}
You need
DispatchQueue.main.async {
self?.getCountdown()
}
As the response of URLSession.shared.dataTask(with: occurs in a background thread

optional type String? not unwrapped

I have a PHP page that is on my webserver that interacts with a mysql database called grabmapinfo.php
The output of the page is [{"companyname":"Brunos Burgers","companyphone":"7745632382","companytown":"858 Western Ave, Lynn, MA 01905"}]
Now I have this Swift code, which I want to get the info from the database, geocode the address to latitude and longitude, plot the annotation on the map, change the annotation image and title, and make a circle with a radius of 5 with the pin being in the center.
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.buyerMapView1.showsUserLocation = true
let url = NSURL(string: "https://alanr917.000webhostapp.com/grabmapinfo.php")
var request = URLRequest(url:url! as URL)
URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in
if error != nil {
// Display an alert message
print(error)
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [[String:AnyObject]] {
for item in json {
// Get company info from DB
let companyname = item["companyname"] as? String
let companyphone = item["companyphone"] as? String
let companytown = item["companytown"] as? String
print("Company : \(companyname)")
print("Phone : \(companyphone)")
print("Address : \(companytown)")
let address = companytown
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, completionHandler: {
(placemarks: [AnyObject]!, error: NSError!) -> Void in
if let placemark = placemarks?[0] as? CLPlacemark {
let pa = MKPointAnnotation()
pa.coordinate = placemark.location.coordinate
pa.title = companyname
pa.imageName = #imageLiteral(resourceName: "growerAnnotation")
self.buyerMapView1.addAnnotation(pa)
let center = annotation.coordinate
let circle = MKCircle(center: center, radius: 5) // change the 5 later to however many miles the grower purchased
self.buyerMapView1.add(circle)
}
})
}
}
} catch {
print(error)
}
})
}
But i get an error that says the optional type String? is not unwrapped and it errors out and wont build.
Does anyone see where I'm going wrong? Thanks!
companyTown is declared as an optional string and the geocodeAddressString method takes a string. You need to unwrap the option before calling it.
if let addressUnwrapped = address {
geocoder.geocodeAddressString(addressUnwrapped, completionHandler: {
(placemarks: [AnyObject]!, error: NSError!) -> Void in
...
})
}
Please check the comments through the code for more detailed explanation on the problems that I found in your code:
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var buyerMapView1: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
buyerMapView1.showsUserLocation = true
// first unwrap your url
guard let url = URL(string: "https://alanr917.000webhostapp.com/grabmapinfo.php") else { return }
print("url:",url)
// no need to create a request. just a url is fine and you don't need to specify the parameters type. Let the compiler infer it.
URLSession.shared.dataTask(with: url) { data, response, error in
// unwrap your data and make sure there is no error
guard let data = data, error == nil else {
print(error ?? "nil")
return
}
// you should update the UI from the main queue
DispatchQueue.main.async {
print("data:", data)
do {
if let array = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
for dict in array {
// make sure you unwrap your dictionary strings
let companyname = dict["companyname"] as? String ?? ""
let companyphone = dict["companyphone"] as? String ?? ""
let companytown = dict["companytown"] as? String ?? ""
print("Company:", companyname)
print("Phone:", companyphone)
print("Address:", companytown)
let address = companytown
let geocoder = CLGeocoder()
// again let the compiler infer the types vvv vvv
geocoder.geocodeAddressString(address) { placemarks, error in
if let placemark = placemarks?.first,
let coordinate = placemark.location?.coordinate {
let pa = MKPointAnnotation()
pa.coordinate = coordinate
pa.title = companyname
self.buyerMapView1.addAnnotation(pa)
let center = pa.coordinate // where does this coordinate come from??
let circle = MKCircle(center: center, radius: 5)
self.buyerMapView1.add(circle)
}
}
}
}
} catch {
print(error)
}
}
// you forgot to call resume to start your data task
}.resume()
}
}

Convert a callback Swift JSON AnyObject into a NSDictionary

I have a network connection with reads the data using JSON and gives a callback;
executeRequestURL(requestURL: url, taskCallback: {(status, resp) -> Void in
if (status == true) {
if let results = resp as? NSDictionary {
print ("\(results.count) results found")
let list = results.allValues.first as! NSArray
print (list)
}
} else {
print ("Error -- \(resp)")
}
})
This calls;
private class func executeRequestURL(requestURL: NSURL, taskCallback: #escaping (Bool, AnyObject?) -> ()) {
print ("Attempting URL -- \(requestURL)")
let request: NSURLRequest = NSURLRequest(url: requestURL as URL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: kAPI_TIMEOUT)
let session: URLSession = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard error == nil else {
print(error)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
//print(json)
if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode {
taskCallback(true, json as AnyObject?)
} else {
taskCallback(false, json as AnyObject?)
}
})
task.resume()
}
The problem I have is that I want to read the results into a dictionary, loop through it and create objects.
For now, I will put my code in the executeRequestURL just to ensure it works, but I intend to seperate this code away for the required entity.
Question:
How do I read the resp as a dictionary?
Thanks
Sample response follows;
{
"objects": [
{
"uid": "coll_20ce39424470457c925f823fc150b3d4",
"title": "Popular",
"temp_image": "",
"body": "",
"active": true,
"slug": "popular",
"created": "2014-10-25T12:45:54+00:00",
"modified": "2014-10-25T12:45:54.159000+00:00",
"ends_on": "2100-01-01T00:00:00+00:00",
}
]
}
As the JSON is a dictionary, return a dictionary ([String:Any]) from the callback. In Swift 3 AnyObject has become Any. The strong type system of Swift encourages to be always as specific as possible.
Do a better error handling! You should return an error rather than just false.
The code uses the new Swift 3 structs URL and URLRequest
private class func executeRequestURL(requestURL: URL, taskCallback: #escaping (Bool, [String:Any]?) -> ()) {
print ("Attempting URL -- \(requestURL)")
let request = URLRequest(url: requestURL, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: kAPI_TIMEOUT)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
guard error == nil else {
print(error)
taskCallback(false, nil)
return
}
guard let data = data else {
print("Data is empty") // <- this will never be reached. If there is no error,
taskCallback(false, nil) // data is always non-nil.
return
}
if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode {
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
taskCallback(true, json)
} else {
taskCallback(false, nil)
}
})
task.resume()
}
The JSON result contains a dictionary with one key objects which contains an array of dictionaries. JSON collection types are very easy to distinguish: {} is dictionary, [] is array.
To map the JSON to objects create a struct
struct Item {
var uid : String
var title : String
var tempImage : String
var body : String
var active : Bool
var slug : String
var created : String
var modified : String
var endOn : String
}
and an array
var items = [Item]()
Then map the dictionaries to Item
if let objects = json["objects"] as? [[String:Any]] {
for object in objects {
let uid = object["uid"] as! String
var title = object["title"] as! String
var tempImage = object["temp_image"] as! String
var body = object["body"] as! String
var active = object["active"] as! Bool
var slug = object["slug"] as! String
var created = object["created"] as! String
var modified = object["modified"] as! String
var endOn = object["end_on"] as! String
let item = Item(uid: uid, title: title, tempImage:tempImage, body: body, active: active, slug: slug, created: created, modified: modified, endOn: endOn)
items.append(item)
}
The JSON values seem to come from a database which includes always all fields so the forced unwrapped values are safe.
I've done it like so:
func getHttpData(urlAddress : String)
{
// Asynchronous Http call to your api url, using NSURLSession:
guard let url = URL(string: urlAddress) else
{
print("Url conversion issue.")
return
}
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
// Check if data was received successfully
if error == nil && data != nil {
do {
// Convert NSData to Dictionary where keys are of type String, and values are of any type
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
// Call whatever function you want to do with your dictionary
useMyDictionary(dictionary: json)
} catch {
print(error)
// Something went wrong
}
}
else if error != nil
{
print(error)
}
}).resume()
}
There are many other ways but I like to do it using ObjectMapper. it looks cleaner to me. So just create a new Swift file, import ObjectMapper and write below code.
class yourDataModel: Mappable {
// MARK: - Constants & Variables
var myObjects: [yourDataModel]
required init?(_ map: Map) {
myObjects = []
}
func mapping(map: Map) {
myObjects <- map["objects"]
}
}
class YourCustomObjects: Mappable {
// MARK: - Constants & Variables
var userId:String
var title:String
var tempimage:String
var body:String
var active:Bool
var slug : String
var createdDate:String
var modifiedDate:String
var endDate:String
// MARK: - init
required init?(_ map: Map) {
userId = ""
title = ""
tempimage = ""
body = ""
active = false
slug = ""
createdDate = ""
modifiedDate = ""
endDate = ""
}
func mapping(map: Map) {
userId <- map["uid"]
title <- map["title"]
tempimage <- map["temp_image"]
body <- map["body"]
active <- map["active"]
slug <- map["slug"]
createdDate <- map["created"]
modifiedDate <- map["modified"]
endDate <- map["ends_on"]
}
}
Basically its your model class, now you just have to pass it your result in JSON which will be an AnyObject hopefully, and it will give you an array containing all your "objects" in it. You can use it like below
if let data = Mapper<yourDataModel>().map(resp){
print(data)
}
Try this, and let me know if you face any difficulty.