使用背景线程在日历上创建多个事件 [英] Creating Multiple Event on Calendar Using Background Thread

查看:155
本文介绍了使用背景线程在日历上创建多个事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须根据服务器的响应(事件)更新日历。我做了一个数组来保存所有的事件对象,并迭代它来保存日历上的事件。它的工作,但问题是它只创建一个随机事件不是所有。


  1. 我必须显示所有事件(最重要的是现在)

  2. 如何使用后台队列更新日历。

  3. 我必须每5分钟更新一次日历,因此方法必须在后台每5分钟执行一次。

  4. 当用户登录到应用程序时,在主页 viewDidLoad 方法中调用服务器以创建事件。日历需要时间来创建事件,如果用户登录并立即退出应用程序,会发生什么。日历会更新还是不更新?我认为在创建日历上的所有活动之前,首页不会加载?

这是代码。

   - (void)calUpdateWebService 
{
NSString * urlString = @http: xxxx.com;

NSURL * url = [NSURL URLWithString:urlString];

NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];

NSURLSessionConfiguration * defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession * defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];

NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData * data,NSURLResponse * response,NSError * error){
if(!error)
{
NSDictionary * responseJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

NSMutableArray * eventArray = responseJson [@result];

eventData = [NSMutableArray new];
for(NSDictionary * eventDict in eventArray)
{
NSDictionary * eventDic = @ {@startDate:[eventDict valueForKey:@start_date],@endDate:[eventDict valueForKey :@end_date],@eventSlot:[eventDict valueForKey:@slot],@eventTitle:[eventDict valueForKey:@package_title]};

[eventData addObject:eventDic];
}
/ **调用方法创建事件** /
[self addBooking];
}

}];
[dataTask resume];
}

/ **创建事件的方法** /
- (void)addBooking
{
EKEventStore * eventStore = [[EKEventStore alloc]在里面];
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,NSError * error){
if(granted)
{
addEventGranted = 1;

EKEvent * event = [EKEvent eventWithEventStore:eventStore];
for(int i = 0; i <[eventData count]; ++ i)
{
[event setTitle:[[eventData objectAtIndex:i] valueForKey:@eventTitle]] ;
NSString * startDate = [[eventData objectAtIndex:i] valueForKey:@startDate];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@yyyy-MM-dd];
NSDate * eventStrtdate = [dateFormatter dateFromString:startDate];
[event setStartDate:eventStrtdate];
[event setEndDate:[[NSDate alloc] initWithTimeInterval:1200 sinceDate:event.startDate]];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError * err;
[eventStore saveEvent:event span:EKSpanThisEvent error:& err];
}
}
}];
} @end


解决方案

你在循环之前实例化一次事件,因此重复更新同一个事件,而你想在循环中实例化一个新事件:

  //不实例化这里
//
// EKEvent * event = [EKEvent eventWithEventStore:eventStore];

for(int i = 0; i <[eventData count]; ++ i){
//但是在这里

EKEvent * event = [EKEvent eventWithEventStore:eventStore];

//现在继续更新事件并保存它
}

在设置一个过程是否在后台运行每5分钟(我假设你的意思,而应用程序不运行),这不是一个通常可能在iOS中的模式。苹果只允许这种连续的后台操作在一个非常狭窄的情况下(导航应用程序,VoIP,音乐应用程序等),因为这种模式会杀死用户的电池(想象如果所有的应用程序都这样做!)。 / p>

请参阅后台执行章节。



但是,有两种方法可以用来完成你所需要的。


  1. 后台抓取:这在上述应用程序编程指南。您无法控制操作系统执行背景提取的频率,但它并不是每五分钟(更可能每天)。操作系统查看用户使用应用程序的频率,新数据的可用频率,设备是否已插入WLAN和Wi-Fi等,以确定其检查更新的频率。


  2. 推送通知,但是它实现类似于你要求的东西。如果您引用本地和远程通知编程指南,您将看到您可以配置您的服务器将通知推送到客户端应用程序,而不是应用程序不断轮询服务器每五分钟更新一次。这是更有效的设计,避免了可能没有任何数据时与服务器的无效查询。



I have to update calendar based on response(events) from the server. I made an array to hold all the event objects and iterating it to save the events on the calendar. Its working but problem is its creating only one random event not all.

  1. I have to show all the events(most important right now).
  2. How to use background queue to update the calendar.
  3. I have to update calendar on every 5minutes, so methods must be execute on every 5 minutes in background.
  4. Making call to the server to create events when my user will loggedIn to the app, in home-page viewDidLoad method. Does calendar takes time to create events, what ll happen if user loggedIn and instantly quit the app. Calendar would be updated or not? I think the Home-page won't be load until all the events on calendar is created?

Here is the code.

- (void)calUpdateWebService
{
    NSString *urlString = @"http://www.xxxx.com";

    NSURL *url = [NSURL URLWithString:urlString];

    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject];

    NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error)
        {
            NSDictionary *responseJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

            NSMutableArray *eventArray = responseJson[@"result"];

            eventData = [NSMutableArray new];
            for(NSDictionary *eventDict in eventArray)
            {
                NSDictionary *eventDic =@{@"startDate":[eventDict valueForKey:@"start_date"],@"endDate":[eventDict valueForKey:@"end_date"],@"eventSlot":[eventDict valueForKey:@"slot"],@"eventTitle":[eventDict valueForKey:@"package_title"]};

                [eventData addObject:eventDic] ;
            }
            /** call method to create events**/
            [self addBooking];
        }

    }];
    [dataTask resume];
}

/** method to create events **/
-(void)addBooking
{
    EKEventStore *eventStore = [[EKEventStore alloc]init];
    [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (granted)
        {
            addEventGranted =1;

            EKEvent *event =[EKEvent eventWithEventStore:eventStore];
            for (int i = 0; i<[eventData count]; ++i)
            {
                [event setTitle:[[eventData objectAtIndex:i] valueForKey:@"eventTitle"]];
                NSString *startDate = [[eventData objectAtIndex:i] valueForKey:@"startDate"];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                NSDate *eventStrtdate = [dateFormatter dateFromString:startDate];
                [event setStartDate:eventStrtdate];
                [event setEndDate:[[NSDate alloc]initWithTimeInterval:1200 sinceDate:event.startDate]];
                [event setCalendar:[eventStore defaultCalendarForNewEvents]];
                NSError *err;
                [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
            }
        }
    }];
}@end

解决方案

The key issue is that you're instantiating your event once, before the loop, therefore updating the same event repeatedly, and you instead want to instantiate a new event within the loop:

// don't instantiate this here
//
// EKEvent *event =[EKEvent eventWithEventStore:eventStore];

for (int i = 0; i<[eventData count]; ++i) {
    // but rather do it here

    EKEvent *event = [EKEvent eventWithEventStore:eventStore];

    // now carry on updating the event and saving it
}

In terms of setting up a process whether this runs every five minutes in the background (I assume you mean while the app is not running), this is not a pattern generally possible in iOS. Apple only allows this sort of continuous background operation in a very narrow set of circumstances (navigation apps, VoIP, music apps, etc.), because this sort of pattern will kill a user's battery (imagine if all apps did this!).

See the Background Execution chapter from the App Programming Guide for iOS.

There are, though, two approaches that you can use to accomplish what you need.

  1. Background Fetch: This is discussed in the aforementioned app programming guide. You don't have control over the frequency with which the OS performs the background fetch, but it's certainly not every five minutes (more likely daily). The OS looks at how often the user uses your app, how often new data is available, whether the device is plugged in and on wifi, etc., to determine the frequency with which it checks for updates. But it accomplishes something similar to what you asked for, albeit far less frequently.

  2. Push Notifications. If you refer to the Local and Remote Notification Programming Guide, you'll see you could configure your server to push notifications to the client app, rather than the app constantly polling the server for updates every five minutes. This is more efficient design, avoiding wasteful inquiries with the server when there might not be any data.

这篇关于使用背景线程在日历上创建多个事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆