调用百度apiStore的天气 自动获取地址 及本地天气

//

//  WeatherView.m

//  CloudSports

//

//  Created by cloudfit on 15/12/10.

//  Copyright © 2015 cloudSports. All rights reserved.

//


#import "WeatherView.h"

#import <CoreLocation/CoreLocation.h>



@interface WeatherView () <CLLocationManagerDelegate>


@property(nonatomic, strong)CLLocationManager *locationManager;



@property (nonatomic, strong) UILabel *tempera;

@property (nonatomic, strong) UILabel *loca;


@end


@implementation WeatherView





//5.实现定位协议回调方法

#pragma mark - CoreLocation Delegate


-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations


{

    

    //此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation

    

    CLLocation *currentLocation = [locations lastObject];


    // 获取当前所在的城市名

    

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    

    //根据经纬度反向地理编译出地址信息

    

    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)

     

     {

         

    

         

         if (array.count > 0)

             

         {

            

             CLPlacemark *placemark = [array objectAtIndex:0];

             

             

             

             //将获得的所有信息显示到label

             

             NSLog(@"城市 === %@",[NSString stringWithFormat:@"%@", [placemark.name substringFromIndex:2]]);

             

             

             

             //获取城市

             

             NSString *city = placemark.locality;

             

             self.loca.text = [NSString stringWithFormat:@"%@", city];

             

             

             

             NSString *httpUrl = @"http://apis.baidu.com/heweather/weather/free";

            

             

             NSRange range = NSMakeRange(0, 2);

             

            NSString *unicodeStr = [[self.loca.text substringWithRange:range] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

             

             NSString *httpArg = [NSString stringWithFormat:@"city=%@",  unicodeStr];

             NSLog(@"%@", httpArg);

             

             [self request: httpUrl withHttpArg: httpArg];

        

             

             if (!city) {

                 

                 //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)

                 

                 city = placemark.administrativeArea;

                 

             }

             

             


             

             

         }

         

         else if (error == nil && [array count] == 0)

             

         {

             

             NSLog(@"No results were returned.");

             

         }

         

         else if (error != nil)

             

         {

             

             NSLog(@"An error occurred = %@", error);

             

         }

         

     }];

    

    //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新

    

    [manager stopUpdatingLocation];

    

}


- (NSString *)chineseToPinyin:(NSString *)chinese withSpace:(BOOL)withSpace {

    CFStringRef hanzi = (__bridge CFStringRef)chinese; CFMutableStringRef string = CFStringCreateMutableCopy(NULL, 0, hanzi); CFStringTransform(string, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform(string, NULL, kCFStringTransformStripDiacritics, NO);

    NSString *pinyin = (NSString *)CFBridgingRelease(string);

    if (!withSpace) {

        pinyin = [pinyin stringByReplacingOccurrencesOfString:@" " withString:@""];

    }

    

    

    return pinyin;

}



- (void)locationManager:(CLLocationManager *)manager


       didFailWithError:(NSError *)error {

    

    

    

    if (error.code == kCLErrorDenied) {

        

        // 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在

        

    }

    

}





//温度和地址

- (void)creatLabel {

    

    

    

    self.tempera = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height / 2)];

    self.tempera.text = @"1000'C";

    self.tempera.font = [UIFont systemFontOfSize:26 weight:0.5];

    self.tempera.textColor = [UIColor whiteColor];

    [self addSubview:self.tempera];

    

    

    self.loca = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.size.height / 2, self.frame.size.width, self.frame.size.height / 2)];

    self.loca.text = @"火星";

    self.loca.textAlignment = 1;

    self.loca.textColor = [UIColor whiteColor];

    [self addSubview:self.loca];

    

    

    

}



- (instancetype)initWithFrame:(CGRect)frame {

    

    self = [super initWithFrame:frame];

    

    if (self) {

        

        // 判断定位操作是否被允许

        

        if([CLLocationManager locationServicesEnabled]) {

            

            self.locationManager=[[CLLocationManager alloc] init];

            self.locationManager.delegate=self;

            self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;

            self.locationManager.distanceFilter=10;

          

            [self.locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8定位需要)

            

            [self.locationManager startUpdatingLocation];//开启定位

            

        } else {

            

            //提示用户无法进行定位操作

            

            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:

                                      

                                      @"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

            

            [alertView show];

            

        }

        

        // 开始定位

        

        [self.locationManager startUpdatingLocation];


        [self creatLabel];

    

        

        

    }

    

    return self;

    

    

    

}


-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {

    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];

    NSURL *url = [NSURL URLWithString: urlStr];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];

    [request setHTTPMethod: @"GET"];

    [request addValue: @"990dad7a6837a25f7ecfd621fcf9f90d" forHTTPHeaderField: @"apikey"];

    [NSURLConnection sendAsynchronousRequest: request

                                       queue: [NSOperationQueue mainQueue]

                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){

                               if (error) {

                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);

                               } else {

                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];

                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

                                   NSLog(@"HttpResponseCode:%ld", responseCode);

                             

                                   

                                   NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];

                                   NSError *err;

                                   NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

                                                                                       options:NSJSONReadingMutableContainers

                                                                                         error:&err];

                                   

                                   

                                   if (responseCode == 200 && [NSArray arrayWithArray:dic[@"HeWeather data service 3.0"]].count != 0) {

                                      // NSLog(@"天气 = %@", dic);

                                       

                                       self.tempera.text = [NSString stringWithFormat:@"%@'C", dic[@"HeWeather data service 3.0"][0][@"now"][@"tmp"]];

                                       

                                   }

                                   

                                   

                                   

                               }

                           }];

    

}




@end



工作忙死 太懒了  直接复制吧


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值