0

I'm trying to make a request to a local host api with Swift. However, JSON data from the api isn't being printed when I run my code. Does Swift/Xcode even allow me to make a url request to a local host api on a specific port? There are no errors showing up in the debug console, so I'm assuming there isn't a problem with my api struct. I'm new to programming so I don't really understand why it's not printing anything in the output console.

My code:

class ShoeViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    
    // Hit API Endpoint
    
    let urlString = "http://localhost:3000/search/:Jordan 1 Retro High Dior"

    let url = URL(string: urlString)

    guard url != nil else {
        
        return
        
    }
    
    let session = URLSession.shared
    
    let dataTask = session.dataTask(with: url!) { (data, response, error) in
        
       // Check for errors
        
        if error == nil && data != nil {
            
            //Parse JSON
            
            let decoder = JSONDecoder()
            
            
            do {
            
                let sneaker = try decoder.decode(sneakerInfo.self, from: data!)
                
                print(sneaker)
                
            }
            catch {
                
                print("Error in JSON parsing.")
                
            }
            
        }
        
    }
    
    //Make API call
    
    dataTask.resume()
    
}

}

API struct:

struct sneakerInfo: Decodable {

var lowestResellPrice:[Int]?
var shoeName:String = ""
var styleID:String = ""
var colorway:String?
var retailPrice:Int?
var thumbnail:String?
var description: String?

}

JSON data in Rested app:

JSON Data that I'm working with

jakelax
  • 1
  • 1
  • 2
    It's not even getting past your guard statement because your URL is nil, because `"http://localhost:3000/search/:Jordan 1 Retro High Dior"` is not a valid URL string. – TylerP Dec 30 '20 at 01:12
  • 1
    Have you set up an api server running on your localhost on port 3000? Further to Tyler’s comment, URLs cannot have spaces and other special characters in them. Those characters need to be %hex encoded if you need to pass them in (e.g., space is `%20`). This old question addresses url encoding in Swift: https://stackoverflow.com/questions/24551816/swift-encode-url – Grant Neufeld Dec 30 '20 at 01:31
  • I'm pretty sure I have an api server on that port. I'm running a third party API from GitHub and when I run it in the terminal it says "API listening on port: 3000". Thanks for these two comments, should help a lot! – jakelax Dec 30 '20 at 11:05

0 Answers0