How to delete event from eventkit - ios

This is the code in my detail view it can delete event in when u come to detail view press the switch to add event and then press it again to delete it. However, when u come to detail view and then press back (using navigation) and then come o the same page again it cannot delete the event please help
there are more function but I delete just focus on Switch and EVENTKIT
//
// DetailScheduleViewController.m
// Register
//
// Created by junejubu on 3/10/2558 BE.
// Copyright (c) 2558 Thananont Aunsiripant. All rights reserved.
//
- (void)viewDidLoad {
[super viewDidLoad];
//NSLog(#"check show id sch ::%#",self.Show_ID);
self.Switch.on = NO;
self.lblNotification.text = #"Notification OFF";
[self getUserNotification];
[self getUserFollow];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getUserNotification
{
NSString *urlStr2 = #"http://ptvshowthai.com/getNotification.php";
NSURL *url2 = [NSURL URLWithString:urlStr2];
self.getnoti = [ASIFormDataRequest requestWithURL:url2];
self.getnoti.requestMethod = #"POST"; //DELETE, PUT
self.getnoti.delegate = self;
self.getnoti.timeOutSeconds = 30;
[self.getnoti setPostValue: self.FK_User_ID forKey:#"sMemberID"];
[self.getnoti setValidatesSecureCertificate:NO];
[self.getnoti startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"requestFinished");
if (request == self.getnoti) {
self.dictnoti = [NSJSONSerialization JSONObjectWithData:[request responseData] options:NSJSONReadingAllowFragments error:nil];
self.NOTI = [[NSMutableArray alloc] init];
for (NSDictionary *dataDic in self.dictnoti )
{
// unsigned long count2 = [self.dict2 count];
NSString *ShowID2 = [dataDic objectForKey:#"Show_ID"];
self.str2 = [dataDic objectForKey:#"Event_Store"];
// NSLog(#"check str2 :: %#",self.str2);
[self.NOTI addObject:ShowID2];
}
NSLog(#"Show who noti ::%#",self.NOTI);
// NSLog(#"check str2 :: %#",self.str2);
}
if(request ==self.getFollow){
self.dict2 = [NSJSONSerialization JSONObjectWithData:[request responseData] options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Dict getFollow :: %#",self.dict2);
//unsigned long count2 = [self.dict2 count];
//NSLog(#"show count ::%lu",count2);
_Show = [[NSMutableArray alloc] init];
// NSDictionary *dict;
for (NSDictionary *dataDic in self.dict2 )
{
// unsigned long count2 = [self.dict2 count];
NSString *ShowID = [dataDic objectForKey:#"Show_ID"];
[self.Show addObject:ShowID];
}
if ([self.Show containsObject: self.Show_ID]) {
_lblFollow.text = #"Following";
_lblFollow.textColor = [UIColor greenColor];
_i = #"0";
NSLog(#"check i green :: %#",_i);
self.Switch.hidden = NO;
NSLog(#"check self.noti : %#",self.NOTI);
if ([self.NOTI containsObject: self.Show_ID]){
self.Switch.on = YES;
}
self.lblNotification.hidden = NO;
[self.Switch addTarget:self action:#selector(Onoff) forControlEvents:UIControlEventValueChanged];
}
else{
_lblFollow.text = #"Follow";
_lblFollow.textColor = [UIColor redColor];
_i = #"1";
NSLog(#"check i red :: %#",_i);
self.Switch.hidden = YES;
self.Switch.on = NO;
self.lblNotification.hidden = YES;
[self.Switch addTarget:self action:#selector(Onoff) forControlEvents:UIControlEventValueChanged];
}
}
}
-(void)addevent{
_eventStore = [[EKEventStore alloc] init];
if ([_eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
[_eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted){
addEventgranted = 1;
EKEvent *event = [EKEvent eventWithEventStore:_eventStore];
[event setTitle:self.showNameTitle];
[event setStartDate: self.today];
[event setEndDate:[[NSDate alloc]initWithTimeInterval:self.duration sinceDate:event.startDate]];
NSTimeInterval alarmOffset = -300;
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:alarmOffset];
[event addAlarm:alarm];
[event setCalendar:[_eventStore defaultCalendarForNewEvents]];
NSError *err;
[_eventStore saveEvent:event span:EKSpanThisEvent error:&err];
self.str = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
NSLog(#"check self.str :: %#",self.str);
NSString *url = #"http://ptvshowthai.com/insertNotification.php";
NSURL *urls = [NSURL URLWithString:url];
self.formData = [ASIFormDataRequest requestWithURL:urls];
self.formData.requestMethod = #"POST";
self.formData.delegate = self;
self.formData.timeOutSeconds = 30;
[self.formData setPostValue: self.FK_User_ID forKey:#"sMemberID"];
[self.formData setPostValue: self.Show_ID forKey:#"showID"];
NSLog(#"check str::: %#",self.str);
[self.formData setPostValue: self.str forKey:#"event"];
[self.formData setValidatesSecureCertificate:NO];
[self.formData startAsynchronous];
_lblFollow.text = #"Following";
_lblFollow.textColor = [UIColor greenColor];
NSLog(#"Follow");
[self getUserNotification];
}
}];
}
}
-(void)alert
{
if (addEventgranted == 1) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success" message:#"Event Successfully added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}
-(void)Onoff
{
if (self.Switch.on) {
[self addevent];
[self performSelector:#selector(alert) withObject:nil afterDelay:0.3];
self.lblNotification.text =#"Notification On";
}
else
{
NSLog(#"check str22::%#",self.str2);
EKEvent* event2 = [_eventStore eventWithIdentifier:self.str2];
if (event2 != nil) {
NSError* error = nil;
[_eventStore removeEvent:event2 span:EKSpanThisEvent error:&error];
}
self.lblNotification.text =#"Notification OFF";
NSString *url = #"http://ptvshowthai.com/deleteNotification.php";
NSURL *urls = [NSURL URLWithString:url];
self.formData = [ASIFormDataRequest requestWithURL:urls];
self.formData.requestMethod = #"POST";
self.formData.delegate = self;
self.formData.timeOutSeconds = 30;
[self.formData setPostValue: self.FK_User_ID forKey:#"sMemberID"];
[self.formData setPostValue: self.Show_ID forKey:#"showID"];
[self.formData setValidatesSecureCertificate:NO];
[self.formData startAsynchronous];
_lblFollow.text = #"Following";
_lblFollow.textColor = [UIColor greenColor];
NSLog(#"Follow");
[self getUserNotification];
}
}

Add below line of code at switch off condition also
Its better to add below line at ViewDidLoad instead of addEvent method..
_eventStore = [[EKEventStore alloc] init];
Hope it fixes..!

Related

Getting delay to see next view controller ,see detail in post?

I have one login screen after that it will move to next view controller which have i have used some networks like http,json to get data from server. when i enter login username/password then if i click login button its getting delay to 8 seconds after that only it moving to next view controller.Still that my login screen alone showing for 8 seconds and then only it move to next view controller.
Here my login controller.m:
#implementation mainViewController
- (void)viewDidLoad {
[super viewDidLoad];
_username.delegate = self;
_password.delegate = self;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:#"reg"]) {
NSLog(#"no user reg");
_logBtn.hidden = NO;
}
}
- (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
_username.text = nil;
_password.text = nil;
}
- (IBAction)LoginUser:(id)sender {
if ([_username.text isEqualToString:#"sat"] && [_password.text isEqualToString:#"123"]) {
NSLog(#"Login success");
[self performSegueWithIdentifier:#"nextscreen" sender:self];
}
else {
NSLog(#"login was unsucess");
// Alert message
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"wrong"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil];
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
}
Here my nextcontroller.m
- (void)viewDidLoad {
[super viewDidLoad];
//for search label data
self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
titleArray = [NSMutableArray array];
// here only i am getting data from server
[self getdata];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView reloadData];
}
Help me out. If my question din't understand.I can tell more about my post. And in my nextcontroller.m [self getdata] is i am getting data from server url.Thanks
My get data:
-(void)getdata {
NSString *userName = #“users”;
NSString *password = #“images”;
NSData *plainData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
base64String=[self sha256HashFor: base64String];
NSString *urlString = #"https://porterblog/image/file”;
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError * error;
self->arrayPDFName = [[NSMutableArray alloc]init];
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictOriginal = jsonResults[#“birds”];
[titleArray addObject:[NSString stringWithFormat:#" birds(%#)”, dictOriginal[#"count"]]];
NSDictionary *dictOriginal2 = jsonResults[#"owl”];
[titleArray addObject:[NSString stringWithFormat:#" Owl(%#)”, dictOriginal2[#"count"]]];
NSDictionary *dictOriginal3 = jsonResults[#"pensq”];
[titleArray addObject:[NSString stringWithFormat:#" Pensq(%#)”, dictOriginal3[#"count"]]];
NSDictionary *dictOriginal4 = jsonResults[#“lion”];
[titleArray addObject:[NSString stringWithFormat:#" lion(%#)”, dictOriginal4[#"count"]]];
NSArray *arrayFiles = [NSArray arrayWithObjects: dictOriginal, dictOriginal2, dictOriginal3, dictOriginal4, nil];
NSLog(#"str: %#", titleArray);
for (NSDictionary *dict in arrayFiles) {
NSMutableArray *arr = [NSMutableArray array];
NSArray *a = dict[#"files"];
for(int i=0; i < a.count; i ++) {
NSString *strName = [NSString stringWithFormat:#"%#",[[dict[#"files"] objectAtIndex:i] valueForKey:#"name"]];
[arr addObject:strName];
}
[arrayPDFName addObject:arr];
}
NSString *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory1 stringByAppendingPathComponent:#"SampleData.plist"];
NSString *error1;
returnData = [ NSPropertyListSerialization dataWithPropertyList:jsonResults format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if(returnData ) {
if ([returnData writeToFile:plistPath atomically:YES]) {
NSLog(#"Data successfully saved.");
}else {
NSLog(#"Did not managed to save NSData.");
}
}
else {
NSLog(#"%#",errorDesc);
}
NSDictionary *stringsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
}
EDITED:
`- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
self.dataSourceForSearchResult = [NSArray new];
titleArray = [NSMutableArray array];
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView reloadData];
self.navigationItem.hidesBackButton = YES;
});
});
}`
You're getting your data using main thread you need do to that in background then invoke the code you need (as i see is reload collectionView)
I assume that because you didn't show the getdata method code
If that the case you can use this code:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.collectionView reloadData];
});
});
It's mean that your VC will show immediately but the collectionView fill after you finish load the data, you can put some old data while loading like Facebook app (you see latest retrieved posts until finish loading].
Edit:
In your code you replace viewdidload method in nextController with next code:
- (void)viewDidLoad {
[super viewDidLoad];
//for search label data
self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
titleArray = [NSMutableArray array];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.collectionView reloadData];
});
});
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
}

removeFromSuperview does not work

I've this piece of code that try to feed an array from a web-service. If it fails, an error message appears, with the possibility to tap on it to retry. But when I tap on it, the error message doesn't disappear, and the spinner doesn't re-appear.
-(void)Load_Commandes{
if(LIB_Error)
{
[LIB_Error removeFromSuperview];
LIB_Error = nil;
}
TABLE_Commandes.hidden = YES;
LIB_Chargement.hidden = NO;
spinner.hidden = NO;
[spinner startAnimating];
tab_Cdes = [self Init_Tableau];
spinner.hidden = YES;
LIB_Chargement.hidden = YES;
if(tab_Cdes != nil)
{
TABLE_Commandes.hidden = NO;
[TABLE_Commandes reloadData];
}
else
{
LIB_Error = [[UILabel alloc] initWithFrame:self.view.frame];
[LIB_Error setTextColor:[UIColor grayColor]];
[LIB_Error setBackgroundColor:[UIColor clearColor]];
[LIB_Error setTextAlignment:NSTextAlignmentCenter];
[LIB_Error setText:#"Erreur de chargement. \nToucher pour réessayer."];
[LIB_Error setNumberOfLines:2];
UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(Load_Commandes)];
[LIB_Error addGestureRecognizer:gesture];
LIB_Error.userInteractionEnabled = YES;
[self.view addSubview:LIB_Error];
}
}
Here is the code I use to call the web-service, in [self Init_Tableau].
NSString *str=[NSString stringWithFormat:URL_ORDERS];
NSURL *url=[NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error: &error];
Thanks you for your help, because I'll become crazy! ^^
UPDATE : I tried by a lot of different ways. But it seems to be impossible to do. Whatever I do, the visual changes are applied only when all treatments are done.
Here is the code of Init_Tableau.
-(NSArray*)Init_Tableau
{
NSMutableArray* a = [NSMutableArray array];
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable) {
NSLog(#"Erreur de chargement 1");
//return nil;
}
NSURLResponse* response;
NSError* error;
NSString *str=[NSString stringWithFormat:URL_ORDERS];
NSURL *url=[NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error: &error];
NSString *responseBody = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
if(error)
{
NSLog(#"Erreur de chargement 2");
return nil;
}
NSError *e = nil;
NSArray* resultList = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:&e];
for(NSDictionary* dico in resultList){
Entete* cde = [[Entete alloc] init];
cde.ncde = [dico objectForKey:NCDE];
cde.nomf = [dico objectForKey:NOMF];
cde.noml = [dico objectForKey:NOML];
cde.prenomf = [dico objectForKey:PRENOMF];
cde.prenoml = [dico objectForKey:PRENOML];
cde.adresse1f = [dico objectForKey:ADRESSE1F];
cde.adresse1l = [dico objectForKey:ADRESSE1L];
cde.adresse2f = [dico objectForKey:ADRESSE2F];
cde.adresse2l = [dico objectForKey:ADRESSE2L];
cde.cpf = [dico objectForKey:CPF];
cde.cpl = [dico objectForKey:CPL];
cde.villef = [dico objectForKey:VILLEF];
cde.villel = [dico objectForKey:VILLEL];
cde.phonef = [dico objectForKey:PHONEF];
cde.phonel = [dico objectForKey:PHONEL];
cde.societef = [dico objectForKey:SOCIETEF];
cde.societel = [dico objectForKey:SOCIETEL];
cde.etatCde = [dico objectForKey:ETATCDE];
cde.moyenPaiement = [dico objectForKey:MOYENPAIEMENT];
cde.fdp = [dico objectForKey:FDP];
cde.mnt = [[dico objectForKey:MNTCDE] floatValue];
[a addObject:cde];
}
return [NSArray arrayWithArray:a];
}

how to reload table view when I'm in a class?

I have a table view on InquiryViewController that I want to be reloaded when I click the update status button. The update status button is a JSON that gets the status of a message.
Here's the code:
-(BOOL)getMessageStatus : (NSMutableArray *)emails : (UIAlertView *)alert : (UIProgressView *)progress : (InquiryLogViewController *)controller
{
_emailsInApi = [[NSArray alloc]init];
_emailsInApi = [[DBManager getSharedInstance]arrayOfEmails];
NSMutableArray *newArrayEmail = [[NSMutableArray alloc]init];
NSString *arrayEmail =#"";
for(int i = 0; i<[_emailsInApi count]; i++){
arrayEmail = [_emailsInApi objectAtIndex:i];
[newArrayEmail addObject:arrayEmail];
}
NSURL *url = [NSURL URLWithString:#"http://www.url.com/API/2.0/message.php"];
NSDictionary *params =#{#"api_key":#"APIKEYIOS",#"action":#"get-message-status",#"email":newArrayEmail};
NSLog(#"params: %#",params);
NSData *paramsData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *paramsString = [[NSString alloc]initWithData:paramsData encoding:NSUTF8StringEncoding];
paramsString = [paramsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
paramsString = [paramsString stringByReplacingOccurrencesOfString:#"%5C" withString:#""];
NSString *post = [NSString stringWithFormat:#"params=%#", paramsString];
NSData *sendData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:sendData];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error)
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response...... = %#", responseString );
//get data frm response
self.responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.responseArray = [self.responseData objectForKey:#"data"];
for(NSDictionary *items in self.responseArray)
{
Inquiry *inq = [[Inquiry alloc]init];
inq.email = [items objectForKey:#"to_email"];
inq.status = [items objectForKey:#"status_id"];
[emails addObject:inq];
}
float newProg = (float)1 - (float)[emails count] / (float)5;
dispatch_async(dispatch_get_main_queue(), ^{
[progress setProgress:newProg animated:YES];
});
dispatch_async(dispatch_get_main_queue(), ^{
[[DBManager getSharedInstance]updateInquirylog:emails];
});
dispatch_async(dispatch_get_main_queue(), ^{
controller.arrayOfEmails = [[DBManager getSharedInstance]loadInquiries];
[controller.tableViews reloadData];
});
dispatch_async(dispatch_get_main_queue(), ^{
[alert dismissWithClickedButtonIndex:0 animated:YES];
});
}
else
{
self.alert = [[UIAlertView alloc] initWithTitle:nil message:error.localizedDescription delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
self.responseData = nil;
[alert show];
}
}];
[task resume];
return YES;
}
My problem here is in: [controller.tableViews reloadData];
It doesn't reload my table. Why? Help me please. Thank you
EDIT: This json is in a class
Ok I'm sorry. I forgot to include my table view method.
Here it is:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID =#"Cell";
tableCellOfInquiryLog *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (tableView == self.searchDisplayController.searchResultsTableView){
if(cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle]loadNibNamed:#"searchCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
Inquiry *inquiry = [searchResult objectAtIndex:indexPath.row];
cell.sInquiry_id.text =[NSString stringWithFormat:#"%d",inquiry.ID];
cell.sName.text = inquiry.name;
cell.sItem.text = inquiry.item_name;
cell.sDate.text = inquiry.dDate;
cell.status.layer.cornerRadius = 10;
if ([inquiry.status isEqual: #"1"]) {
cell.status.backgroundColor = [UIColor greenColor];
}
else if ([inquiry.status isEqual: #"2"]) {
cell.status.backgroundColor = [UIColor orangeColor];
}
else if ([inquiry.status isEqual: #"3"]) {
cell.status.backgroundColor = [UIColor redColor];
}
return cell;
}
else
{
if(cell == nil)
{
cell = [[tableCellOfInquiryLog alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
Inquiry *inquiry = [arrayOfInquiries objectAtIndex:indexPath.row];
cell.inquiry_id.text =[NSString stringWithFormat:#"%d",inquiry.ID];
cell.name.text = inquiry.name;
cell.item.text = inquiry.item_name;
cell.date.text = inquiry.dDate;
cell.status.layer.cornerRadius = 10;
if ([inquiry.status isEqual: #"1"]) {
cell.status.backgroundColor = [UIColor greenColor];
}
else if ([inquiry.status isEqual: #"2"]) {
cell.status.backgroundColor = [UIColor orangeColor];
}
else if ([inquiry.status isEqual: #"3"]) {
cell.status.backgroundColor = [UIColor redColor];
}
return cell;
}
return nil;
}
create a instance of your tableview and the add the given code in which ever method u want to add to [self.nameoftableview reloaddata]
if (indexPath.section ==1) {
cell = [tableView dequeueReusableCellWithIdentifier:section1identifier];
cell = nil;//here i have made it nil
if (!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:section1identifier];
data *newObj = [callingObj.itemslist objectAtIndex:indexPath.row];
UITextView *titlelabel = [[UITextView alloc]initWithFrame:CGRectMake(cell.frame.origin.x+5, cell.frame.origin.y-2, 320, 38)];
titlelabel.textColor = [UIColor redColor];
titlelabel.font= [UIFont fontWithName:#"Times New Roman" size:FONT_SIZE];
titlelabel.text = newObj.title;
titlelabel.scrollEnabled = NO;
titlelabel.editable = NO;
[cell.contentView addSubview:titlelabel];
desView = [[UITextView alloc]initWithFrame:CGRectMake(cell.frame.origin.x,cell.frame.origin.y+25 , 320, i + 160)];
desView.text = newObj.description;
desView.editable = NO;
desView.hidden = NO;
[cell.contentView addSubview:desView];
if (check == NO) {
desView.hidden = YES;
}
}
}
return cell;

UI hanging on background rss parsing

I'm trying to create a simple rss reader. The code works okay, except the UI hangs when the feeds are being updated. I thought I cobbled together the code to get the feed and parse it on a background queue while updating the UI on the mainQueue, but the table hangs pretty badly. Code below:
-(void)refreshFeed2
{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
for (NSString *feed in _feeds) {
// iterate over all feeds
NSLog(#"feed=%#", feed);
NSURL *url = [NSURL URLWithString:feed];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
(void)[conn initWithRequest:request delegate:self];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([data length] == 0 && error == nil) {
// handle empty response
} else if (error != nil) {
// handle error
NSLog(#"Error %#", [error localizedDescription]);
} else if ([httpResponse statusCode] == 200) {
// data present and no errors
[queue addOperationWithBlock:^{
// parse feed on queue
RXMLElement *rss = [RXMLElement elementFromXMLData:data];
RXMLElement *rssChild = [rss child:#"channel"];
RXMLElement* title = [rssChild child:#"title"];
NSArray* items = [[rss child:#"channel"] children:#"item"];
NSMutableArray* result=[NSMutableArray array];
for (RXMLElement *e in items) {
// iterate over the articles
RSSArticle* article = [[RSSArticle alloc] init];
article.sourceTitle = [title text];
article.articleTitle = [[e child:#"title"] text];
article.articleDescription = [[e child:#"description"] text];
article.articleUrl = [NSURL URLWithString: [[e child:#"link"] text]];
NSString *articleDateString = [[e child:#"pubDate"] text];
article.articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
if (article.articleUrl != NULL) {
[result addObject:article];
}
}
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// update table on mainQueue
for (RSSArticle *article in result) {
// iterate over articles
int insertIdx = [_allEntries indexForInsertingObject:article sortedUsingBlock:^(id a, id b) {
RSSArticle *entry1 = (RSSArticle *) a;
RSSArticle *entry2 = (RSSArticle *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:article atIndex:insertIdx];
[self.LeftTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationFade];
}
}];
}];
}
}];
// Stop refresh control
[refreshControl endRefreshing];
}
}
Code that calls refreshFeed2:
- (void)viewDidLoad {
[super viewDidLoad];
self.allEntries = [NSMutableArray array];
self.feeds = [NSArray arrayWithObjects:
#"http://feeds.washingtonpost.com/rss/politics",
#"http://rss.cnn.com/rss/cnn_allpolitics.rss",
#"http://www.npr.org/rss/rss.php?id=1012",
#"http://www.slatedigital.com/support/feeds/rss_kb.php?s=fd5aa35e773dc3177b85a2126583f002",
nil];
}
//add refresh control to the table view
refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self
action:#selector(refreshInvoked:forState:)
forControlEvents:UIControlEventValueChanged];
NSString* fetchMessage = [NSString stringWithFormat:#"Fetching Articles"];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:fetchMessage
attributes:#{NSFontAttributeName:[UIFont fontWithName:#"Helvetica" size:11.0]}];
[self.LeftTableView addSubview: refreshControl];
[self refreshInvoked:self forState:UIControlStateNormal];
}
-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
NSOperationQueue *refreshQueue = [[NSOperationQueue alloc] init];
[refreshQueue addOperationWithBlock:^{
[self refreshFeed2];
}];
}
Any help?
Thanks!
Can you try this? replace
[self refreshInvoked:self forState:UIControlStateNormal];
by
[self performSelectorOnBackground:#selector(refreshFeed2) withObject:nil];
and replace the same instead of
-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
[self performSelectorOnBackground:#selector(refreshFeed2) withObject:nil ];
}

Application hung on loading JSON from FTP, serializing and saving to CoreData [iOS]

May be my question looks strange, but... (hope somebody help me)
There are two methods in which I load some data from FTP. Sometimes application hung on these methods.
Checking internet connection.
If internet avail:
#interface Download : NSObject {
NSOperationQueue *operationQueue;
}
...
if (!operationQueue) {
operationQueue = [NSOperationQueue new];
}
NSInvocationOperation *operation1;
operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(loadIngredientsFromJSON) object:nil];
[operationQueue addOperation:operation1];
NSInvocationOperation *operation2;
operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(loadRecipesFromJSON) object:nil];
[operation2 addDependency:operation1];
[operationQueue addOperation:operation2];
[operationQueue addObserver:self forKeyPath:#"operations" options:0 context:NULL];
Methods loadIngredientsFromJSON & loadRecipesFromJSON
-(void) loadIngredientsFromJSON
{
NSInteger countInBase = [self dataCountInEntity:#"Ingredients"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"ftp://...Ingredients.json"]];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *error = nil;
if (!responseData) {
return;
}
NSDictionary *ingredientsDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (!ingredientsDictionary) {
return;
}
//NSLog(#"%#", [ingredientsDictionary description]);
NSArray *keys = [ingredientsDictionary allKeys];
if (!countInBase && [ingredientsDictionary count]>0) {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
for (int i=0; i<[ingredientsDictionary count]; i++) {
id aKey = [keys objectAtIndex:i];
NSArray *ingrData = [ingredientsDictionary objectForKey:[NSString stringWithFormat:#"%#", aKey]];
NSArray *tmpArray = [NSArray arrayWithObjects:aKey, [ingrData objectAtIndex:0], [ingrData objectAtIndex:1], nil];
Ingredients *ingredient = [NSEntityDescription insertNewObjectForEntityForName:#"Ingredients" inManagedObjectContext:appDelegate.managedObjectContext];
ingredient.code = [NSNumber numberWithInteger:[[tmpArray objectAtIndex:0] integerValue]];
ingredient.name = [tmpArray objectAtIndex:1];
ingredient.units = [tmpArray objectAtIndex:2];
ingredient.type = [NSNumber numberWithInt:1];
[appDelegate.managedObjectContext save:nil];
}
}
}
...
- (void) loadRecipesFromJSON
{
NSInteger missedCount = 0;
NSInteger recipeCode = 0;
NSString *recipesPath = #"ftp://...";
do {
recipeCode ++;
NSString *recipeFileName = [NSString stringWithFormat:#"recipes/%05d.json", recipeCode];
NSString *recipeFileFullPath = [recipesPath stringByAppendingString:recipeFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:recipeFileFullPath]];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *error = nil;
if (!responseData) {
missedCount ++;
continue;
}
NSDictionary *recipeDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (!recipeDictionary) {
missedCount ++;
continue;
}
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSInteger recipeCount = [self isDataExistInEntity:#"Recipes" withCode:[[recipeDictionary objectForKey:#"recipeCode"] integerValue]];
if (recipeCount == 0) {
Recipes *recipe = [NSEntityDescription insertNewObjectForEntityForName:#"Recipes" inManagedObjectContext:appDelegate.managedObjectContext];
recipe.code = [recipeDictionary objectForKey:#"recipeCode"];
recipe.dateUpdated = [recipeDictionary objectForKey:#"dateEdited"];
recipe.inCategory = [recipeDictionary objectForKey:#"inCategory"];
recipe.name = [recipeDictionary objectForKey:#"recipe"];
recipe.difficulty = [recipeDictionary objectForKey:#"difficulty"];
recipe.personCount = [recipeDictionary objectForKey:#"personCount"];
recipe.prepHour = [recipeDictionary objectForKey:#"prepHour"];
recipe.prepMin = [recipeDictionary objectForKey:#"prepMin"];
int seconds = ([recipe.prepMin intValue]*60)+([recipe.prepHour intValue] * 60 * 60);
recipe.prepTime = [NSNumber numberWithInt: seconds];
recipe.isPaid = [recipeDictionary objectForKey:#"isPaid"];
recipe.comment = [recipeDictionary objectForKey:#"comments"];
NSDictionary *ingredients = [recipeDictionary objectForKey:#"ingredients"];
NSArray *keys = [ingredients allKeys];
if ([keys count] > 0) {
for (int i=0; i<[keys count]; i++) {
Join *join = [NSEntityDescription insertNewObjectForEntityForName:#"Join" inManagedObjectContext:appDelegate.managedObjectContext];
join.recipeCode = [recipeDictionary objectForKey:#"recipeCode"];
id aKey = [keys objectAtIndex:i];
join.ingredientCode = [NSNumber numberWithInteger:[aKey integerValue]];
NSString *str = [ingredients objectForKey:aKey];
double num = [str doubleValue];
join.count = [NSNumber numberWithDouble:num];
join.inCart = [NSNumber numberWithInt:0];
}
}
NSDictionary *prepStages = [recipeDictionary objectForKey:#"prepStage"];
keys = [prepStages allKeys];
if ([keys count] > 0) {
for (int i=0; i<[keys count]; i++) {
PrepStages *prepStage = [NSEntityDescription insertNewObjectForEntityForName:#"PrepStages" inManagedObjectContext:appDelegate.managedObjectContext];
prepStage.recipeCode = [recipeDictionary objectForKey:#"recipeCode"];
id aKey = [keys objectAtIndex:i];
prepStage.order = [NSNumber numberWithInteger:[aKey integerValue]];
prepStage.descriptions = [prepStages objectForKey:aKey];
//загрузка картинки
NSString *recipeImageName = [NSString stringWithFormat:#"recipeImages/%05d-%#.jpg", recipeCode, [NSNumber numberWithInteger:[aKey integerValue]]];
NSString *recipeImageFullPath = [recipesPath stringByAppendingString:recipeImageName];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:recipeImageFullPath]];
if (request) {
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (responseData) {
UIImage *image = [UIImage imageWithData:responseData];
prepStage.image = image;
}
}
}
}
[appDelegate.managedObjectContext save:nil];
}
else {
missedCount ++;
continue;
}
} while (missedCount < 10);
}
Sometimes in one of these two methods application hung and control freeze.
Can anybody give me some advice in which line there may be the bug.
I confused...
EDITED
I noticed interesting thing:
Download process starts when app run. It downloads Recipes from server and inserts them to CoreData. If I tap to see recipe list I use appDelegate.managedObjectContext to fetch data. Download also uses appDelegate.managedObjectContext when it want to insert data.
Can this contain problem?

Resources