ios learning note 02 optional type, making weather query app (network access)

lebus tutorial 02

p47 optional variable:

  • Lectotype:
    • Value, equal to xxx or no value
    • nil, only variables declared as optional types can be assigned values
    • Force to unpack!
    • Optional binding:
class FastCar:Car{
    var window:Int? // Optional variable
    override func drive() { the method of the parent class.
        print("Drive fast")

let  fastCar = FastCar()
fastCar.window = 1

if xxx != nil{

}//Execute only when the optional value is not empty

if let xxx = Optional Variables{
    // You can use xxx as the unpacking value of the optional variable.
    // That is to say, if you assign a value to xxx, you can take the same name

p48-57 weather app

No code drawing interface:

  • Import icon and icon of app

  • add controls

  • Add constraint

  • Edit another page:

  • After editing basic controls and constraints

  • Modify load page

  • Add page Jump

  • Cocopods: managing incoming packages

    • Rapid introduction
    • Auto upgrade package
  • Go to the official website to download the client and use the app to operate (it's too intimate, but the past experience is that the network can't move) - using the official app is very brainless and easy to use. Don't worry about the Internet (downloading apps for the first time may be slow)

  • pod init / / create a new project,

  • Just write the package to be imported in the Podfile file

  • p50 weather api and delegate

  • Get the current location of the user:

    • import CoreLocation
  • plist: property list

    • Privacy - Location When In Use Usage Description / / add value
  • delegate:

    • Only variables in CLLocationManager() have no methods
    • Use delegate to use methods
    • Protocol / / the protocol is similar to the interface in java
    • Implement the method in the protocol, then bind the delegate of the variable to itself, and call its own method with its own variable.
// Implement this method in the protocol:
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let lat = locations[0].coordinate.latitude
        let lon = locations[0].coordinate.longitude
// Called when the page appears:
    override func viewWillAppear(_ animated: Bool) {
        locationManager.requestWhenInUseAuthorization()//Request authorization current location
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters//Set the position accuracy, the greater the accuracy, the more power consumption and resource consumption.
        locationManager.requestLocation()// Get location
  • When overriding the viewcontroller's lifecycle method, remember that super. Calls the original method.
  • p51: use alamofire to complete http request
  • Using pod to install Alamofire
  • Register to use openweather to get appid
  • import Alamofire
        AF.request("").response { response in

  • Finally print out the response from other servers.

  • http request method (method, get, post, delete)

  • Dictionary (a data type, key:value)

    • In swift, if value has multiple values, you should specify the variable type:
let dict : [String:Any] = xxx

// Requested parameter resolution:
// Define the type of parameter
    struct WeatherParameters: Encodable {
        let lat: String
        let lon: String
        let appid:String
// Using the parameter encoded
        let weatherPatameter = WeatherParameters(lat: "\(lat)", lon:"\(lon)", appid: appid )

                   method: .get,
                   parameters: weatherPatameter,
                   encoder: URLEncodedFormParameterEncoder .default).response { response in
            // Use SwiftyJSON to transform data:
                                switch response.result {
                       case .success(let value):
                           let json = JSON(value)
                             let name = json["sdfs"].stringValue//If it's empty, it's nil. Can't print it?
                             // string gets that the type is optional, but stringValue comes out as a certain value
                           print("JSON: \(json)")
                       case .failure(let error):
        }//The data is obtained normally.
  • Use expansion pack: SwiftJSON feature pack.
  • Use more official documents
  • Display on the interface.
  • In fact, it's better to create the weather model first (with MVC Architecture)
  • Computing properties (combining functions and properties) what it really is based on other properties
class Weather{
    var temp = 0
    var condition = 0
    var location = " "
    // Calculated trip
    var icon :String{
          switch (condition) {
             case 0...300 :
                 return "tstorm1"
             case 301...500 :
                 return "light_rain"
             case 501...600 :
                 return "shower3"
             case 601...700 :
                 return "snow4"
             case 701...771 :
                 return "fog"
             case 772...799 :
                 return "tstorm3"
             case 800 :
                 return "sunny"
             case 801...804 :
                 return "cloudy2"
             default :
                 return "dunno"
}//Model class
//                        Transfer data to model
                  = Int(t)
                  = name
                  = json["weather",0,"id"].intValue
                           // Change view
                           self.locationLabel.text = name
                           self.TLabel.text = "\(t)˚"
                           self.imageview.image = UIImage(named: "\(")
  • option + k hit ˚
  • Optimize code, separate function and extension
  • p56 connect your new view to the viewController:
  • Jump prepare for segue. Make some preparations before jump to determine which jump is
  • Then the destination after jump (as) will be the type of our destination controller
  • Three kinds of as
    • as as?as!
    • as upward transformation is safe and legal
    • As? Turn into optional as! If it is not, the failure will be reported as an error. Downward transformation may fail.
  • After getting the target viewcontroller object, you can also pass values to the interface
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "searchCity"{
            let vc = segue.destination as! SearchCityViewController
            vc.currentCity = weather.location
  • p57 the user-defined protocol and delegate realize the reverse value transfer of navigation:
  • protocol is similar to interface and only defines methods.
  • The use method is to define the variables of protocol in a class
  • Another class implements the interface of the class, and also implements the methods in the class.
  • The call sequence is from the class that defines the protocol variable to the class that implements the method. When you implement this method, you can get the value from the class that defines the protocol variable.
  • In fact, the feeling is to define an interface, and the functions in the interface are implemented in another class. That is, the implementation of the delay interface. Put the implementation to the user to write. (delegation mode)
  • Improve the app:

Go back to the previous interface: dismiss()

  @IBAction func searchWearher(_ sender: Any) {
        delegate?.didSearchCityBtn(cityName: inputCityTF.text!)
        dismiss(animated: true, completion: nil)
// Implement the functions in the interface:
    func didSearchCityBtn(cityName: String) {
//        print(cityName)
        let patameters = ["q":"\(cityName)","appid":appid]
        let api = ""
        searchWeacher(api: api, parameters: patameters)
38 original articles published, praised 0 and visited 5017
Private letter follow

Tags: JSON network Java Swift

Posted on Mon, 03 Feb 2020 05:30:13 -0800 by bal bal