[iOS 강좌] 오픈API 이용한 날씨 APP 만들기 - 7. CoreLocation

내위치를 기반으로 날씨 정보를 가져올수 있습니다.



// 코어 로케이션
#import <CoreLocation/CoreLocation.h>
// 변수
@property (nonatomic, strong) CLLocationManager *locationManager;
// Location Manager 생성
self.locationManager = [[CLLocationManager alloc] init];
    
// Location Receiver 콜백에 대한 delegate 설정
self.locationManager.delegate = self;
// 델리게이트
<CLLocationManagerDelegate>
// longitude, latitude 값 가져옴
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
   CLLocation *currentLocation = [locations lastObject];
    currentLocation.coordinate.longitude
    currentLocation.coordinate.latitude
}


사용권한을 확인 후 코어 로케이션을 시작합니다.

 // 사용권한 확인, 사용권한이 켜있을 경우 코어 로케이션 START
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
        
        [self.locationManager startUpdatingLocation];   
    }
   
    else if (status == kCLAuthorizationStatusNotDetermined) {
        if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
        {
            [self.locationManager requestWhenInUseAuthorization];
            
        }
    }


날씨 API 중, lat, lon 파라미터를 입력하면 위도,경도 기준으로 날씨 정보를 받아올 수 있습니다.


#import "AFNetworking.h
// get 방식으로 파라미터를 넣어서 호출 / 위도 경도
NSDictionary * parameters =@{
                         @" lat" : @"1835848",
                         @" lon" : @"1835848",
                         @"APPID" : @"f18379cb9ed5dff3d62ad51bab87ba8a",
                         };
[self reqWeatherApi:@"https://api.openweathermap.org/data/2.5/forecast?" parameters:dic];
-(void)reqWeatherApi:(NSString*)url parameters:(NSDictionary*)parameters{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

날씨 모델 객체를 받은 객체와 같이 생성하여 테이블뷰에 노출합니다.
이미지는 비동기 다운로더를 이용하여, 가져옵니다.

// 날씨 모델 객체 생성

WeatherModel  *weatherModel = [m_weatherArray objectAtIndex:indexPath.row];
// 배열 정보 생성
Weather *weather =[Weather mj_objectWithKeyValues:weatherModel.weather[0]];
    
// 날씨 및 날짜
cell.textLabel.text =[NSString stringWithFormat:@"%@, %@",weather.main,
[self convertUTC:weatherModel.dt_txt]];
    
// 디테일 정보
float iTemp =[weatherModel.main.temp floatValue] - 273.15;
cell.detailTextLabel.text =[NSString stringWithFormat:
@"현재온도 : %.1f, 습도 : %@, 바람 : %@,구름 : %@",
iTemp ,weatherModel.main.humidity,weatherModel.wind.speed,weatherModel.clouds.all];
// 날씨 아이콘 -> 이미지 비동기 다운로더
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://openweathermap.org/img/w/%@.png",weather.icon]]
                      placeholderImage:[UIImage imageNamed:@"noimage"] options:SDWebImageRefreshCached];


댓글

주간 인기글

카드뉴스 마케팅 팁

[ubuntu] 신규 계정에 sudo 권한 추가하기

[정보] 인스타그램은 당신의 소리를 '듣고' 있을 수도 있습니다

[Spring Boot] JPA + Pageable 을 이용한 페이징 처리

[네이버클라우드] 서버 인스턴스 생성하기