2014-01-31 1 views
6

UILocalNotification을 설정해야하는데 DatePicker에서 시간과 분이 걸릴 필요가 있으며 (예 : 월요일)을 설정하고 매주 월요일에 반복해야합니다.특정 날짜에 반복 UILocalNotification

나는 그것에 대해 두 가지 질문이 있습니다.

처음으로; 날짜 선택 도구의 날짜 섹션에 '일요일'과 같은 '요일 이름'만 표시 할 수 있습니까?

두 번째 질문은; 현지 알림을위한 특정 날짜를 설정하려면 올바른 코드는 무엇입니까?

해답을 제공해 주셔서 감사 드리며 여기에 제 코드가 있습니다.

-(IBAction) alarmButton:(id)sender { 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
dateFormatter.timeZone = [NSTimeZone defaultTimeZone]; 
dateFormatter.timeStyle = NSDateFormatterShortStyle; 
dateFormatter.dateStyle = NSDateFormatterShortStyle; 

NSString *dateTimeString = [dateFormatter stringFromDate: dateTimePickerSet1.date]; 
NSLog (@"Alarm Set :%@" , dateTimeString); 

[self scheduleLocalNotificationWithDate1: dateTimePickerSet1.date]; 

} 

-(void)scheduleLocalNotificationWithDate1:(NSDate *)fireDate { 
UILocalNotification *notification = [[UILocalNotification alloc] init]; 

notification.fireDate = fireDate; 
notification.alertBody = @"Alarm Set !"; 

[[UIApplication sharedApplication] scheduleLocalNotification:notification]; 
+0

확인 - http://useyourloaf.com/blog/2010/09/13/repeating-an-ios-local-notification.html 또는 c 또한 http://stackoverflow.com/questions/14769462/set-repeatinterval-in-local-notification 또는 http://stackoverflow.com/questions/18014438/repeating-a-local-notification-after-documentation.asp에서 도움을 받으십시오. every-14-daystwo-weeks – Bharat

답변

8

난 당신이 원하는 것을 이해할 수 없다 1 => 질문.

질문 2 =>YES 당신이 올바른 얻을 수 있습니다 (당신이 그런 일요일, 월요일 같은 일의 이름을 표시 할 경우에, .... 토요일에 다음 UIPickerView. 사용) 특정 일의 날짜와 세트 localNotification.repeatInterval = NSWeekCalendarUnit;

를 들어 그것을 달성하여 모든 특정 일에 알림을받을 수 있으며, 또한 (법의) 코드의 조각 다음 사용해야합니다. 이 방법은 특정 선택한 날짜의 정확한 날짜를 반환합니다, 당신은 선택한 날짜 인 경우, 1
을 통과 선택한 날짜가 경우 일요일

, 등 같은 방법의 매개 변수로 통과해야 월요일 다음 패스
.
.
. 선택한 날짜가 토요일 경우
다음 통과 여기에 7

는 방법 코드 :

-(NSDate *) getDateOfSpecificDay:(NSInteger) day /// here day will be 1 or 2.. or 7 
{ 
    NSInteger desiredWeekday = day 
    NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit]; 
    NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1; 

    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]]; 
    NSInteger currentWeekday = dateComponents.weekday; 
    NSInteger differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek; 
    NSDateComponents *daysComponents = [[NSDateComponents alloc] init]; 
    daysComponents.day = differenceDays; 
    NSDate *resultDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:[NSDate date] options:0]; 
    return resultDate; 
} 

그리고 여기 localNotification.repeatInterval = NSWeekCalendarUnit;

+0

응답 해 주셔서 대단히 감사합니다. 답변에 대해서는 조금 더 도움이 필요합니다. 2. 날짜 선택 도구 구성으로 답변을 사용하는 방법에 대한 샘플 코드를 얻을 수 있습니까? 꽤 많이 다시 고맙습니다. @iPatel – Rick

+1

당신의 방법을 이해하기 위해 몇 시간을 보내고 난 후에 그것을 구현하고 이제는 완벽하게 작동했습니다. @iPatel. – Rick

0

을 설정 iPatel의 솔루션 @입니다 잊지 마세요 또한 datepicker를 통해 전달 된 시간 구성 요소의 요소입니다. (나는 그의 솔루션을 사용하지 않는 최신 달력 단위를 사용하도록 업데이트했습니다).

- (NSDate *) getFireDateForDayOfWeek:(NSInteger)desiredWeekday withTime:(NSDate *)time // 1:Sunday - 7:Saturday 
{ 
    NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSCalendarUnitWeekday]; 
    NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1; 

    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]]; 
    NSInteger currentWeekday = dateComponents.weekday; 
    NSInteger differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek; 

    NSDateComponents *daysComponents = [[NSDateComponents alloc] init]; 
    daysComponents.day = differenceDays; 
    NSDate *fireDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:[NSDate date] options:0]; 

    NSDateComponents *timeComponents = [[NSCalendar currentCalendar] components:  NSCalendarUnitHour | NSCalendarUnitMinute fromDate:time]; 
    NSDateComponents *fireDateComponents = [[NSCalendar currentCalendar] 
       components: NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond 
       fromDate:fireDate]; 

    fireDateComponents.hour = timeComponents.hour; 
    fireDateComponents.minute = timeComponents.minute; 
    fireDateComponents.second = 0; 

    NSDate *resultDate = [[NSCalendar currentCalendar] dateFromComponents:fireDateComponents]; 

    // The day could be today but time is in past. If so, move ahead to next week 
    if(resultDate.timeIntervalSinceNow < 0) { 
     resultDate = [resultDate dateByAddingTimeInterval:60 * 60 * 24 * 7]; 
    } 

    return resultDate; 
} 
+0

Oren, 어떻게 지내십니까? 당신? 지난 몇 시간 동안 당신의 코드를 이해하려고 노력 중입니다. 정확히 필요한 것이지만 작동하지 않는 것 같습니다. 최대한 빨리 저에게 연락하십시오. 나는 3 일 동안 뭔가를하고 있었지만 아직도하지 않았습니다. 이 간단한 부분을 그림해라. 토다 아히 :) [email protected] –

0

이 용액은 또한 계정에 시간이 필요하지만,이보다 조금 더 단순화이다 오렌의

여기
-(NSDate *) dateOfSpecificDay:(NSInteger) day withFireTime:(NSDate *)timeDate/// here day will be 1 or 2.. or 7 and timeDate the current day with the desired time 
{ 
    NSInteger desiredWeekday = day; 
    NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSCalendarUnitWeekday]; 
    NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1; 

    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]]; 
    NSInteger currentWeekday = dateComponents.weekday; 
    NSInteger differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek; 
    if (differenceDays == 0) { 
     //Check if should register for same day or for next week 
     if ([timeDate compare:[NSDate date]] == NSOrderedAscending) { 
      //Should schedule for next week 
      differenceDays = daysInWeek; 
     } 
    } 

    NSDateComponents *daysComponents = [[NSDateComponents alloc] init]; 
    daysComponents.day = differenceDays; 
    NSDate *resultDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:timeDate options:0]; 

    return resultDate; 
} 
0

신속 버전 이 예에서는

func calculateTheNExtFriday(inputTime: NSDate) -> NSDate { 
    let desiredWeekday = 6 // Friday 

    let weekDateRange = NSCalendar.currentCalendar().maximumRangeOfUnit(NSCalendarUnit.Weekday) 
    let daysInWeek = weekDateRange.length - weekDateRange.location + 1; 

    let currentWeekday = NSCalendar.currentCalendar().components(NSCalendarUnit.Weekday, fromDate: inputTime).weekday 
    let differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek 

    let dateComponents = NSDateComponents() 
    dateComponents.day = differenceDays 

    let calculatedFridayDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: inputTime, options: NSCalendarOptions.init(rawValue: 0)) 
    return calculatedFridayDate! 
} 

은 함수 내에서 desiredWeekday를 사용하지만 매개 변수로 사용할 수도 있습니다.

NB가 : 하루 1 일요일, 2에 해당하는 것을 염두에 두십시오 -> 월요일과

에 이렇게
0

스위프트 3 :

func calculateSpecificDay(_ desiredWeekday: NSInteger, fromDate: Date = Date()) -> Date { 

    let weekDateRange = NSCalendar.current.maximumRange(of: .weekday)! 
    let daysInWeek = weekDateRange.lowerBound.distance(to: weekDateRange.upperBound) - weekDateRange.lowerBound + 1 

    let currentWeekday = NSCalendar.current.dateComponents([.weekday], from: fromDate).weekday 
    let differenceDays = (desiredWeekday - currentWeekday! + daysInWeek) % daysInWeek 

    var dateComponents = DateComponents() 
    dateComponents.day = differenceDays 

    let calculatedFridayDate = NSCalendar.current.date(byAdding: dateComponents, to: fromDate) 
    return calculatedFridayDate! 
} 
If selected day is sunday then pass 1 
If selected day is monday then pass 2 
. 
. 
. 
If selected day is saturday then pass 7