iOS & Swift 공부 - Working with API's (OpenWeather)

김영채 (Kevin)·2021년 1월 14일
0

iOS & Swift

목록 보기
24/107
  • Application Programming Interface (API)

    → A set of commands, functions, protocols, and objects that programmers can use to create SW or interact with an external system

  • It provides developers with standard commands for performing common operations so they do not have to write the code from scratch

ex. API's to create software: Apple Developer Documentation

ex. API's to interact with an external system: Tinder asking Facebook for access to friends to show some related info

→ it's like a contract between the developer and the provider.

Weather API

  • Normally, in order to prevent abuse of data provided by the API provider, the API provider will ask you to sign up and get assigned a unique "key", so it will be able to identify it is you when you use it.

  • An example of an API call
  • After the question mark (?), q is the parameter for the City, and appid is the variable for our unique API key.
  • The question marks denotes the beginning of the queries (like an input to our Swift functions)


→ If we make the API call within the browser by passing in the parameter appid with our API key and city name, we get the above JSON data. (JSON Viewer download needed from Chrome Extension Store)

  • The parameter order can be in any order

  • add &units = metric for Celsius temperature

  • How do we implement this using Swift?

//WeatherManager.swift

struct WeatherManager{
    
    //Deliberately deleted "q=London" within the url, because it needs to be customizable with a different city
    let weatherURL = "http://api.openweathermap.org/data/2.5/weather?appid=05f127c75b54873b91a8324762be85e4&&units=metric"
    
    func fetchWeather(cityName: String){
        let urlString = "\(weatherURL)&q=\(cityName)"
    }
    
}

//WeatherViewController.swift

var weatherManager = WeatherManager()

func textFieldDidEndEditing(_ textField: UITextField) {
        
        if let city = searchTextField.text{
            weatherManager.fetchWeather(cityName: city)
            
        }
        
        searchTextField.text = ""
}
profile
맛있는 iOS 프로그래밍

0개의 댓글