Reference URL:
Latitude Location: http://blog.csdn.net/whaomian/article/details/6807739
Location Resolution: Http://www.cocoachina.com/bbs/read.php?tid=134893&keyword=%B5%D8%C0%ED%CE%BB%D6%C3
Baidu Weather Free api:http://www.cnblogs.com/txw1958/p/baidu-weather-forecast-api.html
Afnetworking access Network and simple JSON parsing: http://e673.com/index.php/afnetworking-conclu-json/
Address Chinese encoding not recognized in URL: http://blog.csdn.net/typingios/article/details/9136005
Recently, I wanted to learn about positioning and getting the weather. It was very difficult at first, and it took nearly four days to do it and received a lot of goods. As a novice like me, there is a need at first, but do not know how to achieve, a lot of time spent looking for information. In fact, the proficiency of a few time spent.
Go to the Chase:
1. Positioning.
First, add the library corelocaltion.framework to the project. There is no difference between corelocaltion.framework and mapkit.framework, but the expansion of mapkit.framework support maps is even more bloated.
Add a reference to the. h file:
1 #import <CoreLocaltion/CoreLocaltion.h>
Implement Proxy: Cllocationmanagerdelegate
and define two variables:
1 cllocationmanager *Localmanager; 2 cllocation *newlocation;
Initialize the Localmanager in the Viewdidload method in the. m file and set the proxy for yourself:
1 // Initialize Locationmanager 2 Locationmanager = [[Cllocationmanager alloc] init]; 3 // Set positioning accuracy 4 locationmanager.desiredaccuracy = kcllocationaccuracybest; 5 // Set up proxy 6 Locationmanager. delegate = self;
and implement method Locationmanager:didupdatelocations: For processing transactions when positioning is successful
1- (void) Locationmanager: (Cllocationmanager *) Manager didupdatelocations: (Nsarray *) Locations2 {3NewLocation = [Locations Firstobject];//The first one is the current position, the second one is the original position .4 5 //post successful processing, as shown in the View6 //Latitude: newLocation.coordinate.latitude, Longitude: newLocation.coordinate.longitude7 8[Localmanager stopupdatinglocation];//Turn off positioning9}
By the way, the previous method locationManager:didUpdateToLocation:fromLocation:, suggested with the new method above!
1 -(void) Locationmanager: (Cllocationmanager *) Manager didupdatetolocation: (cllocation *) NewLocation fromlocation: (cllocation *) oldlocation {2 newlocation = newlocation; 3 // positioning after successful processing, as above 4 }
The above method from the function name should be able to see, is the location update automatically call method, but the location update is to program control, for example, a button in the program to start updating location when clicked, then in the Click event to add to the location of the service and the location of the request to update:
1 if([Cllocationmanager locationservicesenabled]) {2 //if it's iOS8, you need to manually request a location authorization.3 if(Currentvesion >=8.0) {4 [Locationmanager requestwheninuseauthorization];5 }6 //Update Location7 [Locationmanager startupdatinglocation];8}Else{9 //provides a hint that location services are not available or are not authorized to obtain positional informationTen}
2. Resolving locations
Just get the location information, the following to the location information (defined above) to decode, so you can get the text description of location information, such as "Henan province Kaifeng Jinming Street * * * *".
Add a variable to the. h file: Clplacemark *placemark;//It's not particularly necessary to build this variable here, but to get the weather data back through the weather API.
In the. m file, start decoding. Can be added to the "post-successful Processing" section above:
1 //text string description of location2__block NSString *locationinfo =@"";3 4Clgeocoder *geocoder =[[Clgeocoder alloc] init];5[Geocoder reversegeocodelocation:newlocation completionhandler:^ (Nsarray *placemarks, Nserror *error) {6 if(Placemarks.count >0) {7Placemark = [Placemarks objectatindex:0];8 9Locationinfo = [[Placemark.addressdictionary valueforkey:@"Formattedaddresslines"] Componentsjoinedbystring:@", "];Ten One //Print individual field information for Placemark ANSLog (@"I am currently at%@", locationinfo); -NSLog (@"Placemark. Isocountrycode%@", Placemark. Isocountrycode); -NSLog (@"placemark.country%@", placemark.country); theNSLog (@"Placemark.postalcode%@", Placemark.postalcode); -NSLog (@"Placemark.administrativearea%@", Placemark.administrativearea); -NSLog (@"placemark.locality%@", placemark.locality); -NSLog (@"placemark.sublocality%@", placemark.sublocality); +NSLog (@"Placemark.subthoroughfare%@", placemark.subthoroughfare); - } +}];
3. Get weather using Weather interface
Search on the internet for a long time of the weather interface, found that Baidu is also easy to use (stable, free), it was decisively used Baidu.
Use the interface to access the network to obtain data, so here also pay attention to networking. Online said Afnetworking Good, is also decisive use, first realized out again pick good or bad.
Download the zip package on afnetworking website and add the Afnetworking folder to the project.
Add a reference to the. h file:
1 #import " AFHTTPRequestOperation.h "
To add a variable:
1 // Storage of structured weather data, in order to reuse in the program, it is recommended to use model, and then convenient operation and then sealed up a layer of modelservice 2 nsdictionary *responsedic;
Then, in the Set parameter request data (as in another button event):
1 //Note that the data behind the parameter "AK" must be applied to Baidu when it does its own application2 //parameter "Location", there is said to use latitude and longitude, but I failed to test, I do not know whether it was when I handled the wrong write3 //parameter "Output", specifying the return data type, JSON or XML4 5 //Link String6NSString *requeststr = [NSString stringWithFormat:@"http://api.map.baidu.com/telematics/v3/weather?location=%@&output=json&ak=******", placemark.locality];7 //link string, UTF8 format, this I do not intentionally set in another demo to UTF8 also normal use8NSString *weatherrequeststr =[Requeststr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];9 //URL linkTenNsurl *weatherrequesturl =[Nsurl Urlwithstring:weatherrequeststr]; One //Request ANsurlrequest *weatherrequest =[Nsurlrequest Requestwithurl:weatherrequesturl]; - - //The AF library provides a request operation that initializes theAfhttprequestoperation *weatherrequestoperation =[[Afhttprequestoperation alloc]initwithrequest:weatherrequest]; - //set callback function for successful and failed request operation -[Weatherrequestoperation setcompletionblockwithsuccess:^ (Afhttprequestoperation *operation,IDresponseobject) { -NSLog (@"The request was successful! "); + - //parsing json with Nsjsonserialization +NSString *responsestr =[NSString stringWithString:operation.responseString]; ANSLog (@"%@", responsestr); atNSData *responsedata =[[NSData alloc] initwithdata:[responsestr datausingencoding:nsutf8stringencoding]]; -Responsedic =[nsjsonserialization jsonobjectwithdata:responsedata options:nsjsonreadingmutableleaves Error:nil]; -} failure:^ (Afhttprequestoperation *operation, Nserror *error) { -NSLog (@"request failed:%@", error); - }]; - //Start request Operation in[Weatherrequestoperation start];
4. Analyze Weather Data
After getting the structured weather data, you can read the data, using JSON. The parsing of JSON is actually a value operation for Nsarray and Nsdictionary. It is recommended to encapsulate the service in the appropriate model for ease of use.
Beginners Note: It is important to carefully analyze the structure of JSON (XML) when accessing data, otherwise you will spend a long time looking for errors, in the middle may also think that is the function method write error. In the JSON file, the data in the middle of "{" and "}" is the data of type nsdictionary, the data in the middle of "[" and "]" is nsarray type, especially when several "{" or "}" and "[" or "]" are next to each other, it must be parsed and then written.
OK, so far, you can write a small application of your own weather.
IOS-Location and weather access analysis