Implementing a weather forecast app with Swift (i)

Source: Internet
Author: User

Swift is a fast-growing language that Apple is now promoting. This language, like her name, cuts down a lot of files and code volumes than OC. header file, bye bye, no need to check the code up and down the header file source file switch. And the language itself has added a lot of security considerations, such as the class initialization phase of the check. Not in accordance with the provisions of the written can not be compiled through! This article assumes that you have a certain programming foundation, and a certain swift foundation. If the wood has, please look here quickly to fill up.

This article uses the swif to write an app, lets you together to realize the swift exactly is fortunately where. For simplicity, the tutorial uses storyboard instead of manually adding controllers and various views of the controller's view. Using storyboard can reduce the amount of code. This will be reflected in the following tutorial. Any view jumps are the lines that follow ctrl and are segue. These standard jumps do not have to write a single line of code.

Now the app, no one is isolated in the user's mobile phone. In addition, the amount, similar to 2048 such an app does not have the obvious connection to the background of the server, but your location and other information has been uploaded to the backend server. So, our tutorial also involves the network connection. Use the SDK built-in first, then explain the very popular afnetworking now.

The app for the weather forecast looks like this:

Now get to the point and create our project:

Select a single view's template. And then:

After completing the project name, Swift weather and other such as, organization name, etc. After the next step, you are sure to create the project.

This time you will see that there is a xib file in addition to storyboard. This xib file is not intended to be used in conjunction with Viewcontroller in the app. Instead, it is designed to fit different screen resolutions. That is, with this file called Launchscreen.xib, you do not have to make a picture of launchimage at every resolution.

Here's one thing to watch out for. This launchscreen nib file is not bound to Iboutlet and ibaction after the file owner is set like the Xib files we used to use. Since this nib file is loaded, the app has not been loaded yet, so even the viewcontroler that bind file owner is not available.

Below we begin to wear a different scene (corresponding to a uiviewcontroller) in the storyboard and connect them together. Before this, we need to understand how this app will work. Here, we are relatively simple, do not think of Sina weather, ink weather. Because, this is after-school homework. After watching the tutorial by yourself to achieve a similar live better weather forecast client. Our demo weather app is relatively simple. The user opens the app and then goes directly to the app's weather main screen to see the weather. The user can then click the "City" button on the left side of the navigation bar to change cities alive by clicking the "Refresh" button on the right to refresh the weather data in real time.

The head of the main interface will look like this:

OK, come back to storyboard. First, drag a uinavigationcontroller from the right-side utilities Sidebar:

Come up to storyboard and set the initial Controller,

Dragging a uinavigationcontroller will bring a rootviewcontroller up. Check this controller and delete it. We're going to use our own controller as a rootviewcontroller. After deleting from the right to the menu select a Viewcontroller, and put the mouse on the Uinavigationcontroller, and then press Ctrol button, with the mouse slowly drag a blue and blue line to your new home on the Viewcontroller. Let go of CTRL. Select the bottom relationship->rootviewcontroller in the pop-up menu. When the connection is complete, a segue is generated.

This app is ready to run, press Command+r and the app will appear in the simulator. Although the interface is very simple now.

The basic structure is already there, and the main interface element is added below. Looking closely at the interface, you can find a pattern:

The general structure is at the top of the display location, the following Big sun is the current weather conditions, and then below is the current temperature. A row of small plots below the main interface is the time-phased weather and temperature. The order of the display is the time, the picture of the weather and the temperature at that time. The small structure is the above text, the middle picture, the following is also the text. The biggest difference is that the main screen of the big picture section above shows the place name, and the following time shows the weather section, which shows the time. So, the structure of the topic is poor, from the top to the bottom of the order shows the text picture and then the text. Remember this first, and you'll use this rule in the back. Now, let's drag the elements you need on the interface to the Viewcontroller view in this pattern. Use the shortcut key option+command+l, and then enter the label. You will appear in the sidebar on the right to uilabel this control, drag to the view. The others are dragged to the main interface in turn. Then bind the controller file in the storyboard. The corresponding code file for the main interface is Mainviewcontroller, and the corresponding iboutlet for each control is added to the code. Just like this:

@IBOutlet weakvaricon:uiimageview!@IBOutlet Weakvartemperature:uilabel!@IBOutlet Weakvarloading:uilabel!@IBOutlet Weakvarlocation:uilabel!@IBOutlet Weakvartime1:uilabel!@IBOutlet Weakvartime2:uilabel!@IBOutlet Weakvartime3:uilabel!@IBOutlet Weakvartime4:uilabel!@IBOutlet Weakvarimage1:uiimageview!@IBOutlet Weakvarimage2:uiimageview!@IBOutlet Weakvarimage3:uiimageview!@IBOutlet Weakvarimage4:uiimageview!@IBOutlet Weakvartemp1:uilabel!@IBOutlet Weakvartemp2:uilabel!@IBOutlet Weakvartemp3:uilabel!@IBOutlet Weakvartemp4:uilabel!

You can now bind the storyboard controls and the Iboutlet in the Mainviewcontroller. Binding order: First, in the storyboard to select the scene of the main interface, second, point to the place of the circle, this time in the sidebar will find that there is a section of iboutlet that we have just defined in the code properties. As shown on the left, there is an icon which is the attribute of the definition mentioned in the code above.

When binding, put the mouse on the back of a small circle, such as icon, and then hold down the CTRL key, drag the mouse to the control you want to bind, release the CTRL key binding is complete. Just like the Textlabel effect in the left-hand image. Point that small fork to break the binding of the corresponding property in the control and code.

After binding, you can modify properties such as the values of these controls in your code. Well-bound:

This assumes that you have placed the elements of the interface in the same way as the main interface, set them up, and are already bound. If you have any questions, please refer to the source code.

One thing must be mentioned here. The reason why many companies do not use nib files and the current storyboard. Because, as you can see, the use of nib or the storyboard file will have a lot of names, a slight modification may forget where there is no rebinding. Without a bound control, a crash may occur when it is run. Because, when the control is accessed according to Key-value, no bindings are found. There are many other places that need to be named, including Ibaction and segue. Although, storyboard has this bad place. For individual developers, however, the amount of code is actually reduced. Also greatly improve the speed of development! So the merit of storyboard is still very obvious.

That's what it looks like when all the controls are put in place.

The above is almost a matter of talking about the interface. You will see that there are two other places not mentioned. One is city, one is refresh. These two buttons are used to replace the city and refresh the data. After the city has been lit up, the user can select a different town to view the weather information for that site. After clicking Refresh, you can retrieve the local weather data and refresh the data on the main screen. A "unwind segue" knowledge point is involved in the interface element of the city button. relatively simple. In the following tutorial, continue to explain.

Our weather is based on the user's location to get and display. At least when the user first enters the app, the app automatically obtains the user's geo-location information and accesses the server information to get weather data based on the location information. So, the first problem is to go to the user's geographical location, that is, latitude and longitude.

Detailed information on how to obtain a location under IOS8 can be seen in this article. Here's a simple word. Getting location information is used in the corelocation framework. There is no need to specifically introduce the framework into the XCODE6. As long as you look at the frame name in the code with import.

// Get a location

The user's consent is required to obtain the user's geographic location, so the user's consent (in iOS8) needs to be requested in the code first. The text that asks for the user's consent must be configured in the project's plist file. The configuration in this plist is a must! Otherwise, the app does not get the user's geographic location.

The way to get a geographic location is the same as other versions of iOS, setting up proxies, getting a geographic location in the agent, or handling errors from getting information.

class Viewcontroller:uiviewcontroller, Cllocationmanagerdelegate

Above is the implementation of Locationmanagerdelegate, the following is the specified agent, set the accuracy and request user consent and so on.

 Self.locationmanager.        delegate  = self;        Self.locationManager.desiredAccuracy  = kcllocationaccuracybest Self.locationManager.distanceFilter  = Kcllocationaccuracykilometer  Span style= "color: #0000ff;" >if  self.locationManager.respondsToSelector ( " requestalwaysauthorization   "  "  requestalwaysauthorization   ) Self.lo Cationmanager.requestalwaysauthorization ()}  

This sentence if Self.locationManager.respondsToSelector ("Requestalwaysauthorization") is intended to be compatible with systems prior to iOS8.

Finally, see how Locationmanager's agent gets the location and how to handle the error.

//mark:corelocationmanagerdelegateFunc Locationmanager (manager:cllocationmanager!, didupdatelocations locations: [anyobject]!) {println ("Get Location")        varLocation:cllocation = locations[locations.count-1] ascllocationif(Location.horizontalaccuracy >0) {self.locationManager.stopUpdatingLocation () println (location.coordinate) Self.tex Tlabel.text="latitude \ (location.coordinate.latitude) longitude \ (location.coordinate.longitude)"}} func Locationmanager (Manager:cllocationmanager!, Didfailwitherror error:nserror!) {println (error) Self.textLabel.text="Get location Error"    }

The error handling here only shows the wrong text in the label that displays the specific latitude and longitude. For a better user experience, the wrong hints can be made in a more friendly way. Here's just a brief talk here.

The first part of the app is introduced here. More content will continue to be explained in a later tutorial.

Implementing a weather forecast app with Swift (i)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.