您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 倒數計時實作:電商搶購活動剩餘時間計算

編輯:iOS 相關教學

電商大促的頁面上幾乎少不了那一行跳動的數字:「距活動結束還剩 X 天 X 時 X 分 X 秒」。這種倒數計時在 iOS 端該怎麼算?其實核心只有一個 NSCalendar 的 components:fromDate:toDate:options:,它能直接幫你算出兩個時間點之間的年、月、日、時、分、秒差值,不必自己去做進位運算。

關鍵程式碼如下:

 /** * 倒數計時 * * @param endTime 截止時間戳 * * @return 回傳剩餘時間字串 */ - (NSString*)remainingTimeMethodAction:(long long)endTime { //取得當前時間 NSDate *nowData = [NSDate date]; NSDate *endData=[NSDate dateWithTimeIntervalSince1970:endTime]; NSCalendar* chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar ]; NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit; NSDateComponents *cps = [chineseClendar components:unitFlags fromDate:nowData toDate: endData options:0]; NSInteger Hour = [cps hour]; NSInteger Min = [cps minute]; NSInteger Sec = [cps second]; NSInteger Day = [cps day]; NSInteger Mon = [cps month]; NSInteger Year = [cps year]; NSLog( @" From Now to %@, diff: Years: %d Months: %d, Days; %d, Hours: %d, Mins:%d, sec:%d", [nowData description], Year, Mon, Day, Hour, Min,Sec ); NSString *countdown = [NSString stringWithFormat:@"還剩: %zi天 %zi小時 %zi分鐘 %zi秒 ", Day,Hour, Min, Sec]; if (Sec<0) { countdown=[NSString stringWithFormat:@"活動結束/開始搶購"]; } return countdown; }

實務上有幾點要補充:這個方法只負責「算出字串」,真正的跳動要靠 NSTimer 或 GCD 的 dispatch_source 每秒呼叫一次,記得在 view 消失時把計時器清掉,否則容易閃退或耗電。另外時間基準建議統一以伺服器時間為準(本地存一個時間差偏移量),使用者改用手機時間才不會把倒數弄壞。程式碼很簡單,大家可依實際需求增減欄位,有疑問歡迎留言討論。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved