ios – Code working perfectly fine for the first time but when the button is tapped again, nothing happens

[ad_1]

I was making an app in Xcode using storyboard and the app basically takes fetches time zone information based on a place user provides.
The app contains a simple textfield and a search button associated with it. The user is supposed to enter the name of a place and the app taps into an api, to fetch information of that place in json format. The json data has been decoded perfectly and parsed into a struct and then passed back to the view controller.Then the ui labels are updated based on the fetched values and everything works fine for the first time but as soon as the search button is tapped, nothing happens.

____NewViewController.swift-----

import UIKit

class NewViewController: UIViewController {

    
    var clockManager = ClockManager()
    
    @IBOutlet weak var requestedLocationLabel: UILabel!
    @IBOutlet weak var dAndTLabel: UILabel!
    @IBOutlet weak var latitudeLabel: UILabel!
    @IBOutlet weak var timezoneNameLabel: UILabel!
    @IBOutlet weak var longitudeLabel: UILabel!
    @IBOutlet weak var textFieldLabel: UITextField!
    @IBOutlet weak var timezoneLocationLabe: UILabel!
   
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        textFieldLabel.delegate = self
        clockManager.delegate = self
       // textFieldLabel.delegate = self
    }
    
    @IBAction func searchButtonTappeedd(_ sender: UIButton) {
       
       // clockManager.delegate = self
        textFieldLabel.endEditing(true)
    }
    /*@IBAction func searchTapped(sender: UIButton) {
        textFieldLabel.endEditing(true)
    }*/
}


extension NewViewController: ClockManagerDelegate{
    
    
    func didFetchTime(_ clockManager: ClockManager ,time: ClockModel) {
        DispatchQueue.main.async {
            self.requestedLocationLabel.text = time.requested_location
            self.dAndTLabel.text = time.datetime
            self.latitudeLabel.text = String(time.latitude)
            self.longitudeLabel.text = String(time.longitude)
            self.timezoneLocationLabe.text = time.timezone_location
            self.timezoneNameLabel.text = time.timezone_name
            print("success")
        }
    }
    
    func didFailWithError(error: Error){
        print(error)
    }
    
    
}


extension NewViewController: UITextFieldDelegate{
   
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textFieldLabel.endEditing(true)
        //print(searchTextField.text!)`enter code here`
        return true
        
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if textField.text != " "{
            return true
        }else{
            textField.placeholder = "Type Something"
            return false
        }
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        
        if let city = textFieldLabel.text{
            print("sbra")
            self.clockManager.fetchTime(cityName: city)
            
            
            
            
            print("first checkpoint working")
        }
        
        textField.text = " "
        
    }
    
}
-----ClockManager.swift-----
//
//  ClockManager.swift
//  worldClock
//
//  Created by suhail on 02/09/22.
//

import Foundation
import UIKit

protocol ClockManagerDelegate: UITextFieldDelegate{
    func didFetchTime(_ clockManager: ClockManager ,time: ClockModel)
    func didFailWithError(error: Error)
}
struct ClockManager{
    
    var delegate: ClockManagerDelegate?
    
    let timeUrl = "https://timezone.abstractapi.com/v1/current_time?api_key=c00f5fc842a44c0285efd263375faf08&location"
    
    func fetchTime(cityName: String){
        
        let urlString = "\(timeUrl)=\(cityName)"
        performRequest(with: urlString)
        print("Checkpoin a")
    }
    
    
    
    //Networking Function
    func performRequest(with urlString: String){
        //1. Create a URL
        print("Inside perform request: \(urlString)")
        if let url = URL(string: urlString){
            
            //2. Create a session
            let session = URLSession(configuration: .default)
            print("checkpoin B")
            //3. Give the session a task
            
            let task = session.dataTask(with: url) { data, response, error in
                print("checkpoin c")
                if error != nil{
                    delegate?.didFailWithError(error: error!)
                    // print("something happened")
                    return
                }
                
                if let safeData = data{
                    if let clock = self.parseJSON(safeData){
                        
                        self.delegate?.didFetchTime(self, time: clock)
                        print("Intermission")
                    }
                }
            }
            //4.Start the task
            task.resume()
        }
        
    }
    
    func parseJSON(_ clockData: Data)->ClockModel?{
        let decoder = JSONDecoder()
        do{
            let decodedData = try decoder.decode(ClockData.self, from: clockData)
            let dAndT = decodedData.datetime
            let timezoneName = decodedData.timezone_name
            let reqLoc = decodedData.requested_location
            let lat = decodedData.latitude
            let lon = decodedData.longitude
            let timeZoneLocation = decodedData.timezone_location
            let country = ClockModel(datetime: dAndT, timezone_name: timezoneName, timezone_location: timeZoneLocation, requested_location: reqLoc, latitude: lat, longitude: lon)
            print("inside parseJson")
            
            return country
            
        }catch{
            delegate?.didFailWithError(error: error)
            //print("something happened")
            return nil
        }
    }
    
    
    
    
    
}





-----ClockData.swift-----
import Foundation

struct ClockData: Decodable{
    
    let datetime: String
    let timezone_name: String
    let timezone_location: String
    let requested_location: String
    let latitude: Double
    let longitude: Double
    
    
    
}
-----ClockModel.swift-----
import Foundation

struct ClockModel{
    
    let datetime: String
    let timezone_name: String
    let timezone_location: String
    let requested_location: String
    let latitude: Double
    let longitude: Double
    
}

[ad_2]

Source link

Leave a Reply

Your email address will not be published.