Using Swift to implement a weather forecast app (ii)

Source: Internet
Author: User

In the previous article mainly talked about the interface of some content, this article mainly discusses the network request, get weather data. Specifically, the HTTP request Weather site API, get the JSON data returned. Parse the data and update it into the interface content. Let the user know the current and the next few hours of weather conditions.

The main purpose of initiating HTTP requests is the Nsurlsession class of the SDK, which allows you to create a request task and process the JSON data returned by the server after the request in this task. The main use before the nsurlsession is nsurlconnection. These two classes are more similar. Only the requests that were executed in the background were added in the nsurlsession. When initiating a network request, use Nsurlsession to create the corresponding nsurlsessiontask, and this task requests the server and processes the returned data.

Here's a general look at how we do HTTP requests. This article will mainly describe how to initiate an HTTP request. Let's start with the SDK for the most basic iOS and then describe how to use the Afnetworking framework request that compares the current flow. Maybe you've heard of a frame called asihttprequest, but it's been a long time since no one has maintained it. So, it is no longer mentioned here.

To initiate an HTTP network request using the iOS SDK:

1. Prepare the Nsurl object to access the server. This object requires a URL string, such as Baidu's address string is "http://www.baidu.com", we need a string pointing to the weather server.

var " http://api.openweathermap.org/data/2.5/forecast?lat=\ (latitude) &lon=\ (longitude) " var url = nsurl (string: Weatherurl)

The last part of the first sentence? Lat=\ (latitude) &lon=\ (longitude) is the specified user's current latitude and longitude for the URL. The Nsurl object is then generated based on this URL string.

2. Create the Nsurlsession object. Nsurlsession has a class method to create an instance of.

Self.urlsession = Nsurlsession.sharedsession ()

The usual way to name a sharexxx is to use a single-instance method. This means that the method is called to determine if the required instance has been created, and if so, to return the created instance, if not created, to initialize one and save it for the next use. For a singleton mode using Swift, please refer to here.

3. Create the Nsurlsessiondatatask and set up how to handle the data returned by the request. The HTTP request is then started.

varTask = Self.urlSession.dataTaskWithURL (url!, Completionhandler: {data:nsdata!, response:nsurlresponse!, error: nserror!)inch        ifError! =Nil {println ("HTTP request error \ (Error)")            return} println ("\ (response)")        varHttpResponse = response asNshttpurlresponsevarStatuscode:nsinteger =Httpresponse.statuscode println ("Status code: \ (StatusCode)")                    varError:nserror?varJsondictionary = Nsjsonserialization.jsonobjectwithdata (data, options:NSJSONReadingOptions.AllowFragments, error: &error) asnsdictionaryifError! =Nil {println ("JSON error")            return} println ("JSON \ (jsondictionary)") Self.jsonLabel.text=jsondictionary.description}) task.resume ()

Self.urlSession.dataTaskWithURL This method creates a datatask. Completionhandler is followed by the specified method of processing the returned data. The closure of the Swit is used here. The syntax of a closure can be summarized simply as {(parameter list ...). ), the return type of the closed package in the function code here} specific reference to the above code example. So specifically, what should we do with the returned data? The first step is to see if the error returned is empty. If it is empty is not wrong, otherwise, is wrong. This time you can prompt the user to return directly, no longer deal with the following code.

The following is a check of response's StatusCode. Status code The most intuitive is that we have seen the 404, dried shrimp are found when the hint. If it is, then the request server is successful. Otherwise, you can also prompt the user to return.

Finally, the user data is parsed. First, you need to convert the JSON-formatted data returned by the server to the nsdictionarythat Swift can access directly. Remember, this is nsdictionary is not a generic dictionary<keytype in the swift underlying data type , Valuetype>. Once the JSON data of the server is converted into nsdictionary, it is possible to retrieve the data and update it to the main interface.

Here you will find that many of the code calls are based on whether the Nserror instance is empty to determine if an error occurred in the execution of a function. Swift does not have a Try-catch exception handling mode. There is only such an error in the way. This people need to get used to. The error is handled in this way to remove the two meaning of the code. There are other language programming managers who know that sometimes they use try-catch to make certain judgments about code. That's not right.

The last call to the task's resume method begins the HTTP request.

The previous article has simply mentioned the function of positioning. This article discusses the functionality of the HTTP request before it is here. As mentioned earlier, the request for weather data will need to use latitude and longitude data as the URL parameter. Therefore, the HTTP request can only be performed after the location has been successfully fetched to the user's current latitude and longitude. Therefore, when the code is implemented, the network request is initiated in the proxy method where location manager is positioned successfully.

Func 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)"                        //initiate an HTTP request hereSelf.updateweatherwith (Location.coordinate.latitude, Longitude:location.coordinate.longitude)} }

So far, the ability to request the weather server's JSON data from the user's location to the user's latitude and longitude data has been linked together.

So, let's discuss how to use the Afnetworking Framework (framework). Before this, the user needs to configure Cocoapods. The specific steps can be referred to here. There must be a slot here, Ruby and other sites such as programming the wall is really unreasonable ah. After the configuration, Pro, you must click on the time workspace The suffix of the file, not the project file. Otherwise, there will be an error.

To use the afnetworking framework involves a objective-c and swift interaction problem.

Let manager = Afhttprequestoperationmanager ()

This line of code compiles directly without passing ... A little deeper into the opportunity to discover that there is no way to directly use OC (OBJECTIVE-C) code in Swift. Turn over the project, locate the swiftweather-bridging-header.h header file, and add a reference to the afnetworking framework inside.

#import <AFNetworking/AFNetworking.h>

After you have added, compile your project. The code on the wrong line is ready to use.

It's really handy to use the afnetworking framework. Don't write as much code as you do with nsurlsession. This will come to a conclusion through a simple sensory comparison. The HTTP request code on the afnetworking first.

Let manager =afhttprequestoperationmanager () Let URL="Http://api.openweathermap.org/data/2.5/forecast"println (URL) letparams= ["lat": Latitude,"Lon": Longitude,"CNT":0] println (params) Manager. GET (URL, Parameters:params, Success: {(Operation:afhttprequestoperation!, Responseobject:anyobject!)inch            //println ("JSON:" + responseobject.description!)self.updateuisuccess (Responseobject asnsdictionary!)}, Failure: {(operation:afhttprequestoperation!, Error:nserror!)inchprintln ("Error:"+error.localizeddescription) Self.loading.text="Internet appears down!"        })

A class is sufficient to initialize a Afhttprequestoperationmanager to handle processing of requests and data returns. No more task or anything. Specifies the URL string to access, which is the string and does not require an instance of Nsurl. The parameters that need to be added to the URL string are then placed in a dictionary<string, string> generic dictionary. The manager then makes an HTTP request and specifies how the request is to GET, and the name of the function is the way the HTTP request is made. HTTP requests are also available in many other than get, the most common of which is post. You can then see the sucess and failure in the Get method, respectively, in the process code that specifies the successful request and the processing code that failed.

Using Swift to implement a weather forecast app (ii)

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.