Share Extension is not showing data -- ios - ios

I am trying to create a share Extension. I am showing them into Table view. My data is coming but i am not able to see. Also it freezes (Like we have data and popup but not showing).
here is my sample code
//
// ShareViewController.m
// myAppShare
//
//
//
//
#import "ShareViewController.h"
#import "MBProgressHUD.h"
#import MobileCoreServices;
static NSString *const AppGroupId = #"group.tag.BiblioHive7";
#implementation ShareViewController
{
NSArray *arrayCategory;
__weak IBOutlet UITextField *textFieldCategoryName;
__weak IBOutlet UIButton *btnPost;
__weak IBOutlet UIBarButtonItem *btnCancel;
__weak IBOutlet UINavigationItem *nayTitle;
__weak IBOutlet UINavigationBar *navBar;
}
-(void)viewDidLoad
{
sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:AppGroupId];
[sharedUserDefaults setObject:#"hello" forKey:#"hello"];
NSString *userId= [sharedUserDefaults objectForKey:#"userId"];
NSLog(#"%#", [[sharedUserDefaults objectForKey:#"categories"] class]);
NSError* error;
[self didSelectPost];
if (userId==nil || [userId isEqualToString:#""] )
{
[self hideBackground];
self.view.hidden= YES;
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Error"
message:#"Please login into myApp"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self hideExtentionView];
}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
else
{
self.view.hidden= NO;
id jsonObject = [NSJSONSerialization JSONObjectWithData:[sharedUserDefaults objectForKey:#"categories"] options: NSJSONReadingMutableContainers error:&error];
arrayCategory= [NSArray arrayWithArray:jsonObject];
// here i am able to print object
NSLog(#"%#", [arrayCategory class]);
NSMutableArray *cityArray = [[NSMutableArray alloc] init];
NSMutableArray *testFeeds = [NSJSONSerialization JSONObjectWithData: [sharedUserDefaults objectForKey:#"categories"] options:NSJSONReadingMutableContainers error:nil];
[cityArray addObjectsFromArray:testFeeds];
NSLog(#"%lu", (unsigned long)[cityArray count]);
// [self.tableViewmyApp reloadData];
// here you must have to provide your app group id that you already created
}
}
-(void) hideBackground
{
[self.view setBackgroundColor:[UIColor clearColor]];
[self.tableViewmyApp setBackgroundColor:[UIColor clearColor]];
[textFieldCategoryName setBackgroundColor:[UIColor clearColor]];
[nayTitle setTitle:#""];
[btnPost setHidden:YES];
[navBar setHidden:YES];
}
- (BOOL)isContentValid {
// Do validation of contentText and/or NSExtensionContext attachments here
return YES;
}
- (void)didSelectPost {
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
// Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
inputItem = self.extensionContext.inputItems.firstObject;
NSItemProvider *urlItemProvider = [[inputItem.userInfo valueForKey:NSExtensionItemAttachmentsKey] objectAtIndex:0];
if ([urlItemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypeURL])
{
[urlItemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error)
{
if (error)
{
NSLog(#"Error occured");
}
else
{
if ([sharedUserDefaults objectForKey:#"userId"]==nil)
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:#"Error"
message:#"You must be logged In to share"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:nil];
[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
return;
}
NSMutableArray *previousUrlsArray = [[NSMutableArray alloc]initWithArray:[sharedUserDefaults objectForKey:#"urlsArray"]];
if (previousUrlsArray==nil)
{
previousUrlsArray =[[NSMutableArray alloc]init];
}
[previousUrlsArray addObject:url.absoluteString];
NSMutableDictionary *dict= [[NSMutableDictionary alloc]init];
[dict setObject:previousUrlsArray forKey:#"urls"];
[sharedUserDefaults setObject:dict forKey:#"urlsDictionary"];
[sharedUserDefaults setObject:previousUrlsArray forKey:#"urlsArray"];
// [sharedUserDefaults synchronize];
[sharedUserDefaults setObject:url.absoluteString forKey:#"siteURL"];
[sharedUserDefaults setObject:[NSString stringWithFormat:#"%#",url.absoluteString] forKey:#"sURL"];
NSLog(#"%#",[sharedUserDefaults objectForKey:#"sURL"]);
// NSMutableArray *arrSites;
// if ([sharedUserDefaults valueForKey:#"SharedExtension"])
// arrSites = [sharedUserDefaults valueForKey:#"SharedExtension"];
// else
// arrSites = [[NSMutableArray alloc] init];
// NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, #"Text", url.absoluteString, #"URL",nil];
// [arrSites addObject:dictSite];
// [sharedUserDefaults setObject:arrSites forKey:#"SharedExtension"];
// [sharedUserDefaults synchronize];
// UIAlertController * alert= [UIAlertController
// alertControllerWithTitle:#"Success"
// message:#"Posted Successfully."
// preferredStyle:UIAlertControllerStyleAlert];
//
// UIAlertAction* ok = [UIAlertAction
// actionWithTitle:#"OK"
// style:UIAlertActionStyleDefault
// handler:^(UIAlertAction * action)
// {
// [UIView animateWithDuration:0.20 animations:^
// {
// self.view.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height);
// }
// completion:^(BOOL finished)
// {
// [self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
// }];
// }];
//
// [alert addAction:ok];
// [self presentViewController:alert animated:YES completion:nil];
}
}];
}
}
- (NSArray *)configurationItems {
// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
return #[];
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
/*
* If the cell is nil it means no cell was available for reuse and that we should
* create a new one.
*/
if (cell == nil) {
/*
* Actually create a new cell (with an identifier so that it can be dequeued).
*/
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"] ;
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
}
cell.textLabel.text=[[arrayCategory objectAtIndex:indexPath.row] valueForKey:#"category_name"];
return cell;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrayCategory count];
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self saveInUserDefaultsWithCategoryName:[[arrayCategory objectAtIndex:indexPath.row] valueForKey:#"category_name"] andId:[[[arrayCategory objectAtIndex:indexPath.row] valueForKey:#"id"] integerValue]];
}
- (IBAction)postBtnTapped:(id)sender {
[self saveInUserDefaultsWithCategoryName:textFieldCategoryName.text andId:-1];
}
-(void) saveInUserDefaultsWithCategoryName : (NSString*) categoryName andId : (NSInteger) categoryId
{
if ([categoryName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length==0)
{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Please choose a category or create a new one "
message:#""
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
return;
}
NSString *stringId=[sharedUserDefaults objectForKey:#"id"];
([stringId length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:#"%#,%ld",stringId, (long)categoryId] forKey:#"id"] : [sharedUserDefaults setObject:[NSString stringWithFormat:#"%ld", (long)categoryId] forKey:#"id"];
NSLog(#"%#", [sharedUserDefaults objectForKey:#"id"]);
NSString *stringCategoryName=[sharedUserDefaults objectForKey:#"category_name"];
([stringCategoryName length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:#"%#,%#",stringCategoryName, categoryName] forKey:#"category_name"] : [sharedUserDefaults setObject:[NSString stringWithFormat:#"%#",categoryName] forKey:#"category_name"];
NSLog(#"%#", [sharedUserDefaults objectForKey:#"category_name"]);
NSString *stringURL=[sharedUserDefaults objectForKey:#"URL"];
([stringURL length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:#"%#,%#",stringURL, [sharedUserDefaults objectForKey:#"sURL"]] forKey:#"URL"] : [sharedUserDefaults setObject:[NSString stringWithFormat:#"%#",[sharedUserDefaults objectForKey:#"sURL"]] forKey:#"URL"];
NSLog(#"%#", [sharedUserDefaults objectForKey:#"URL"]);
NSDictionary *categoryDictionary = [NSDictionary dictionaryWithObjectsAndKeys:categoryName,#"categoryName", nil];
NSArray *categoryArray = [NSArray arrayWithObject:categoryDictionary];
NSMutableDictionary *mainDictionary = [[NSMutableDictionary alloc]init];
[mainDictionary setObject:categoryArray forKey:#"categories"];
[mainDictionary setObject:#"0" forKey:#"categoryType"];
[mainDictionary setObject:[sharedUserDefaults objectForKey:#"siteURL"] forKey:#"url"];
[mainDictionary setObject:[sharedUserDefaults objectForKey:#"access_token"] forKey:#"access_token"];
AppServices *appServices = [AppServices sharedInstance];
appServices.delegate = self;
[appServices postCategoriesOnServer:mainDictionary withSucessBlock:nil withfailureBlock:nil];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
// [self enableUserInteraction:NO];
// [[AppServices sharedInstance] sendData:nil withSucessBlock:nil withfailureBlock:nil];
// [sharedUserDefaults setObject:[NSNumber numberWithInteger:categoryId] forKey:#"id"];
// [sharedUserDefaults setObject:categoryName forKey:#"category_name"];
// NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
//
// [dict setObject:categoryName forKey:#"category_name"];
// [dict setObject:[NSNumber numberWithInteger:categoryId] forKey:#"id"];
// NSLog(#"%#", [sharedUserDefaults objectForKey:#"siteURL"]);
//
// [dict setObject:[sharedUserDefaults objectForKey:#"siteURL"] forKey:#"siteurl"];
//
//
// [sharedUserDefaults setObject:[self dictToJson:dict] forKey:#"categorydictionary"];
}
-(NSString *)dictToJson:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict
options:(NSJSONWritingOptions) (/* DISABLES CODE */ (YES) ? NSJSONReadingMutableContainers : 0)
error:&error];
if (! jsonData) {
NSLog(#"bv_jsonStringWithPrettyPrint: error: %#", error.localizedDescription);
return #"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
- (IBAction)cancelBtnTapped:(id)sender {
[self hideExtentionView];
}
-(void) hideExtentionView
{
[self.extensionContext completeRequestReturningItems: nil completionHandler: nil];
}
-(void) showAlertViewWithMessage:(NSString *)message
{
UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[self hideExtentionView];
}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
-(void)enableUserInteraction:(BOOL)enable
{
[self.view setUserInteractionEnabled:enable];
}
#pragma mark- AppServicesDelegate methods
-(void)showMessage:(NSString *)message
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
// [self enableUserInteraction:YES];
[self showAlertViewWithMessage:message];
}
#end

Your problem is that you want to populate table cell textLabel with an array object which is not saved with key value.
In
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
method you try to take an object which is not saved yet on that key.
cell.textLabel.text=[[arrayCategory objectAtIndex:indexPath.row] valueForKey:#"category_name"];
and in
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self saveInUserDefaultsWithCategoryName:[[arrayCategory objectAtIndex:indexPath.row] valueForKey:#"category_name"] andId:[[[arrayCategory objectAtIndex:indexPath.row] valueForKey:#"id"] integerValue]];
}
method, here you save the object.
This is a bad practice.

Related

Table View is not displaying Data

you can download this project from this link
Execute this Program Clicking on button"Click here to sell your Gold now" enter the
username :hermon_yonaito#bullionscope.com
password :Wau2017?
Issue -1
It will launch you to dashboard. Select "Transaction History" that is not displaying record. Check why record is not displaying?And to display the record in view Controller?
Issue-2
The second issue is on selecting Profile the ProfileViewController.m is executed.On updating the user profile updateButtonTap function is executed.It does not update.It remains buffering.How to perform profile update?
here is ProfileViewController.m
#import "ProfileViewController.h"
#interface ProfileViewController ()
#end
#implementation ProfileViewController
- (void)viewDidLoad
{
[super viewDidLoad];
currentUser = [SingletonClass sharedSingletonClass].settingsDictionary[#"User"];
selectedValues=[NSMutableDictionary dictionary];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSMutableDictionary *paramDict=[NSMutableDictionary dictionary];
[paramDict setObject:#"ios" forKey:#"request"];
[paramDict setObject:[NSString stringWithFormat:#"%#",currentUser.user_id] forKey:#"user_id"];
[GeneralWebservices webserviceMainSplashCall:paramDict webserviceName:Webservice_Profile OnCompletion:^(id returnDict, NSError *error) {
if ([returnDict[#"success"] intValue] ==1)
{
[self setProfileData:returnDict[#"data"]];
provinceList=[NSMutableArray arrayWithArray:returnDict[#"provincedata"]];
questions1Array=[NSMutableArray arrayWithArray:returnDict[#"questiondata"]];
}
else
{
[self get_register_data];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];
}
-(void)setProfileData:(NSMutableDictionary*)dataDict
{
profilePicImageView.imageURL=[NSURL URLWithString:dataDict[#"image_file_thumb"]];
[firstNameLabel setText:dataDict[#"first_name"]];
[lastNameLabel setText:dataDict[#"last_name"]];
[dateOfBirthLabel setText:dataDict[#"user_dob"]];
[postalAddressTextfield setText:dataDict[#"user_address"]];
[mobileTextfield setText:dataDict[#"user_mobile"]];
[question1Textfield setText:dataDict[#"user_answer_1"]];
[question2Textfield setText:dataDict[#"user_answer_2"]];
[LLGButton setTitle:dataDict[#"user_llg"] forState:UIControlStateNormal];
[provinceButton setTitle:dataDict[#"user_province"] forState:UIControlStateNormal];
[districtButton setTitle:dataDict[#"user_district"] forState:UIControlStateNormal];
[villageTextfield setText:dataDict[#"user_village"]];
[question1Button setTitle:dataDict[#"user_question_1"] forState:UIControlStateNormal];
[question2Button setTitle:dataDict[#"user_question_2"] forState:UIControlStateNormal];
[self callforDistrict:#"get_district.php" idForItem:dataDict[#"district_id"]];
[self callforLLG:#"get_llg.php" idForItem:dataDict[#"llg_id"]];
[selectedValues setObject:dataDict[#"user_question_1_id"] forKey:#"user_question_1"];
[selectedValues setObject:dataDict[#"user_question_2_id"] forKey:#"user_question_2"];
[selectedValues setObject:dataDict[#"province_id"] forKey:#"user_province"];
[selectedValues setObject:dataDict[#"district_id"] forKey:#"user_district"];
[selectedValues setObject:dataDict[#"llg_id"] forKey:#"user_llg"];
}
-(void)callforDistrict:(NSString*)serviceName idForItem:(NSString*)idForItem
{
dispatch_async(dispatch_get_main_queue(), ^{
[self getdistdata:idForItem];
});
}
-(void)callforLLG:(NSString*)serviceName idForItem:(NSString*)idForItem
{
dispatch_async(dispatch_get_main_queue(), ^{
[self getIIL:idForItem];
});
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidLayoutSubviews
{
[profileScrollView setContentSize:CGSizeMake(self.view.frame.size.width, 700)];
}
- (IBAction)uploadPictureButtonTap:(UIButton *)sender
{
UIActionSheet *popup = [[UIActionSheet alloc] initWithTitle:#"Select option" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:
#"Open Gallery",
#"Take Photo",
nil];
popup.tag = 1;
[popup showInView:[UIApplication sharedApplication].keyWindow];
}
- (IBAction)provinceButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *provinceNames=[NSMutableArray array];
for (NSMutableDictionary*pro in provinceList)
{
[provinceNames addObject:pro[#"province_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Province" buttonTitles:provinceNames cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=2;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)districtButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *names=[NSMutableArray array];
for (NSMutableDictionary*pro in districList)
{
[names addObject:pro[#"district_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select District" buttonTitles:names cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.heightMax=200;
sheet.tagOfSheet=3;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)LLGButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *names=[NSMutableArray array];
for (NSMutableDictionary*pro in llgList)
{
[names addObject:pro[#"llg_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select LLG" buttonTitles:names cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.heightMax=200;
sheet.tagOfSheet=4;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)villageButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
}
- (IBAction)question1ButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *ques1=[NSMutableArray array];
for (NSMutableDictionary*pro in questions1Array)
{
[ques1 addObject:pro[#"question_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Question 1" buttonTitles:ques1 cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=5;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)question2ButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
NSMutableArray *ques2=[NSMutableArray array];
for (NSMutableDictionary*pro in questions1Array)
{
[ques2 addObject:pro[#"question_name"]];
}
LGActionSheet *sheet=[[LGActionSheet alloc] initWithTitle:#"Select Question 2" buttonTitles:ques2 cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil];
sheet.tagOfSheet=6;
sheet.heightMax=300;
sheet.delegate=self;
[sheet showAnimated:YES completionHandler:nil];
}
- (IBAction)updateButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[selectedValues setObject:#"ios" forKey:#"request"];
[selectedValues setObject:[NSString stringWithFormat:#"%#",currentUser.user_id] forKey:#"user_id"];
[selectedValues setObject:postalAddressTextfield.text forKey:#"address"];
[selectedValues setObject:mobileTextfield.text forKey:#"user_mobile"];
[selectedValues setObject:question1Textfield.text forKey:#"user_answer_1"];
[selectedValues setObject:villageTextfield.text forKey:#"user_village"];
[GeneralWebservices webserviceCallWithData:selectedValues webserviceName:Webservice_ProfileUpdate dataToPost:imageData imageName:imageName OnCompletion:^(id returnDict, NSError *error) {
if ([returnDict[#"success"] intValue] ==1)
{
}
else
{
UIAlertView* alert = [[UIAlertView alloc] init];
[alert setTitle:#"Updated Successfully"];
//[alert setMessage:returnDict[#"message"]];
[alert addButtonWithTitle:#"OK"];
[alert show];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];
}
- (IBAction)saveButtonTap:(UIButton *)sender
{
[self.view endEditing:YES];
}
- (void)actionSheet:(LGActionSheet *)actionSheet buttonPressedWithTitle:(NSString *)title index:(NSUInteger)index
{
dispatch_async(dispatch_get_main_queue(), ^{
if (actionSheet.tagOfSheet==2)
{
[selectedValues setObject:provinceList[index][#"province_id"] forKey:#"user_province"];
[provinceButton setTitle:provinceList[index][#"province_name"] forState:UIControlStateNormal];
[districList removeAllObjects];
[llgList removeAllObjects];
[districtButton setTitle:#"District *" forState:UIControlStateNormal];
[LLGButton setTitle:#"LLG *" forState:UIControlStateNormal];
[selectedValues removeObjectForKey:#"district"];
[selectedValues removeObjectForKey:#"llg"];
[self callforDistrict:#"get_district.php" idForItem:provinceList[index][#"province_id"]];
}
else if(actionSheet.tagOfSheet==3)
{
[selectedValues setObject:districList[index][#"id"] forKey:#"user_district"];
[districtButton setTitle:districList[index][#"district_name"] forState:UIControlStateNormal];
[llgList removeAllObjects];
[LLGButton setTitle:#"LLG *" forState:UIControlStateNormal];
[selectedValues removeObjectForKey:#"llg"];
[self callforLLG:#"get_llg.php" idForItem:districList[index][#"id"]];
}
else if(actionSheet.tagOfSheet==4)
{
[selectedValues setObject:llgList[index][#"id"] forKey:#"user_llg"];
[LLGButton setTitle:llgList[index][#"llg_name"] forState:UIControlStateNormal];
}
else if(actionSheet.tagOfSheet==5)
{
[selectedValues setObject:questions1Array[index][#"question_id"] forKey:#"user_question_1"];
[question1Button setTitle:questions1Array[index][#"question_name"] forState:UIControlStateNormal];
}
else if(actionSheet.tagOfSheet==6)
{
[selectedValues setObject:questions1Array[index][#"question_id"] forKey:#"user_question_2"];
[question2Button setTitle:questions1Array[index][#"question_name"] forState:UIControlStateNormal];
}
});
}
-(IBAction) returnTextField:(id)sender
{
CGRect frame = self.view.frame;
frame.origin.y = 0;
[UIView animateWithDuration:0.3 animations:^{
self.view.frame = frame;
}];
[self.view endEditing:YES];
}
- (BOOL)textFieldShouldEndEditing:(UITextField*)textField
{
return YES;
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
[self animateTextField:textField up:NO];
[textField resignFirstResponder];
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[self animateTextField:textField up:YES];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self animateTextField:textField up:NO];
}
- (void)actionSheet:(UIActionSheet *)popup clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch (popup.tag) {
case 1: {
switch (buttonIndex) {
case 0:
[self openPhotoLibraryButton:self];
break;
case 1:
[self openCameraButton:self];
break;
default:
break;
}
break;
}
default:
break;
}
}
- (IBAction)openCameraButton:(id)sender
{
[self.view endEditing:YES];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
picker.allowsEditing = false;
[self presentViewController:picker animated:true completion:nil];
}
else{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Camera is not connected" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
- (IBAction)openPhotoLibraryButton:(id)sender
{
[self.view endEditing:YES];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
picker.allowsEditing = true;
[self presentViewController:picker animated:true completion:nil];
}
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
imageData=[[NSData alloc]init];
if ([info[#"UIImagePickerControllerMediaType"] isEqualToString:#"public.image"])
{
UIImage *image = [info objectForKey:#"UIImagePickerControllerEditedImage"];
if (!image)
{
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
}
NSURL *imagePath = [info objectForKey:#"UIImagePickerControllerReferenceURL"];
image=[SettingsClass rotateImageAppropriately:image];
NSString *imageNamewithformat = [imagePath lastPathComponent];
imageName=#"assets.jpg";
NSString *Imageformat = [imageNamewithformat substringFromIndex: [imageNamewithformat length] - 3];
if ([Imageformat isEqualToString:#"JPG"]||[Imageformat isEqualToString:#"jpg"]) {
imageData=UIImageJPEGRepresentation(image, 0.33f);
imageName=#"assets.jpg";
}
else if ([Imageformat isEqualToString:#"PNG"]||[Imageformat isEqualToString:#"png"])
{
imageData=UIImagePNGRepresentation(image);
imageName=#"assets.png";
}
else
{
imageData=UIImageJPEGRepresentation(image, 0.33f);
imageName=#"assets.jpg";
}
[profilePicImageView setImage:image];
}
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
CGPoint temp = [textField.superview convertPoint:textField.frame.origin toView:nil];
UIInterfaceOrientation orientation =
[[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationPortrait){
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 264-(self.view.frame.size.height-moveUpValue-35);
}
}
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) {
if(up) {
int moveUpValue = self.view.frame.size.height-temp.y+textField.frame.size.height;
animatedDis = 264-(self.view.frame.size.height-moveUpValue-35);
}
}
else if(orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 352-(self.view.frame.size.height-moveUpValue-100);
}
}
else
{
if(up) {
int moveUpValue = temp.y+textField.frame.size.height;
animatedDis = 352-(768-moveUpValue-100);
}
}
if(animatedDis>0)
{
const int movementDistance = animatedDis;
const float movementDuration = 0.3f;
int movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: nil context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
if (orientation == UIInterfaceOrientationPortrait){
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else if(orientation == UIInterfaceOrientationPortraitUpsideDown) {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else if(orientation == UIInterfaceOrientationLandscapeLeft) {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
else {
self.view.frame = CGRectOffset( self.view.frame, 0, movement);
}
[UIView commitAnimations];
}
}
- (IBAction)backtohomeview :(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)getdistdata:(NSString*)idForItem
{
self.view.userInteractionEnabled = NO;
NSString *strURL;
strURL = [NSString stringWithFormat:#"http://bullionscope.com/Gold_Phase3/webservices/get_district.php?request=ios&province_id=%#",idForItem];
NSDictionary *headers = #{ #"cache-control": #"no-cache",
#"postman-token": #"900e1577-4876-cd9a-d24c-cb0631b4a1fb" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// [self AlertController:#"Alert!" :#"Request time out"];
}
else
{
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *success = [[jsonDic objectForKey:#"success"]stringValue];
if (
[success isEqualToString:
#"1"])
{
districList=[NSMutableArray arrayWithArray:[jsonDic objectForKey:#"data"]];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
else
{
// [self AlertController:#"Alert!" :#"No record found"];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
}
}];
[dataTask resume];
}
-(void)get_register_data
{
self.view.userInteractionEnabled = NO;
NSString *strURL;
http://bullionscope.com/Gold_Phase3/webservices/get_all_province.php?request=ios
strURL = [NSString stringWithFormat:#"http://bullionscope.com/Gold_Phase3/webservices/get_all_province.php?request=ios"];
NSDictionary *headers = #{ #"cache-control": #"no-cache",
#"postman-token": #"900e1577-4876-cd9a-d24c-cb0631b4a1fb" };
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// [self AlertController:#"Alert!" :#"Request time out"];
}
else
{
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *success = [[jsonDic objectForKey:#"success"]stringValue];
if (
[success isEqualToString:
#"1"])
{
provinceList=[NSMutableArray arrayWithArray:[jsonDic objectForKey:#"data"]];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
else
{
// [self AlertController:#"Alert!" :#"No record found"];
dispatch_async(dispatch_get_main_queue(), ^{
self.view.userInteractionEnabled = YES;
});
}
}
}];
[dataTask resume];
}
#end
Your api is returning nil data .
here is the error description -
Error Description: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
Problem is with your api handling .
This replace method in your GeneralWebservices class with this
+(void) webserviceMainSplashCall:(NSMutableDictionary *)parameters webserviceName:(NSString*)webserviceName OnCompletion:(void(^)(id returnDict, NSError* error))callbackBlock{
/*
// parameter keys & values, values will be dynamic.
"forward_date" = "26-05-2016";
"gold_weight" = 345;
request = ios;
"user_id" = 1;
*/
NSString *url = [NSString stringWithFormat:#"%#%#",App_BaseUrl,webserviceName];
NSLog(#"url is this = %#", [NSString stringWithFormat:#"%#%#",App_BaseUrl,webserviceName]);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
AFJSONResponseSerializer *jsonReponseSerializer = [AFJSONResponseSerializer serializer];
// This will make the AFJSONResponseSerializer accept any content type
jsonReponseSerializer.acceptableContentTypes = nil;
manager.responseSerializer = jsonReponseSerializer;
// manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/html",#"text/json", #"text/javascript", nil];
// manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:[NSString stringWithFormat:#"%#%#",App_BaseUrl,webserviceName] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
}
progress:^(NSProgress * _Nonnull uploadProgress)
{
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
callbackBlock( responseObject, nil );
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
// check error here.
NSLog(#"Error Description: %#",error);
callbackBlock( nil, nil );
}];
}
final screen shot of output -

What does JGDownloadAcceleration class used to accelerate download and does it is as good as NSURLSession?

I have used "JGDownloadAcceleration" for multipart download and also accelerate the download speed.
From JGDownloadAcceleration
Does it supports background download and also pause and resume of downloads?
UPDATE
I have used below code to start download for any valid URL
-(void)addFinalyDownloadTask:(NSString*)fileName andFilePath :(NSString*)filePath andDestinationPath:(NSString*)fileDestination
{
NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:file])
{
[[[UIAlertView alloc]initWithTitle:nil message:#"This file is already downloading." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil] show];
return;
}
if (!self.ArrayDownloading)
{
self.ArrayDownloading=[[NSMutableArray alloc]init];
}
NSMutableDictionary *dictInfo=[[NSMutableDictionary alloc]init];
[dictInfo setObject:fileName forKey:kDownloadKeyFileName];
[dictInfo setObject:fileDestination forKey:kDownloadKeyFilePath];
[dictInfo setObject:[self getCurrentFolderName:fileDestination] forKey:kDownloadKeyFolderName];
[dictInfo setObject:filePath forKey:kDownloadKeyURL];
[dictInfo setObject:#"0" forKey:kDownloadKeyProgress];
[dictInfo setObject:#"In Queue" forKey:kDownloadKeyDetails];
[dictInfo setObject:RequestStatusDownloading forKey:kDownloadKeyStatus];
[self.ArrayDownloading addObject:dictInfo];
NSMutableArray *arrayDownloding = [[[NSUserDefaults standardUserDefaults] objectForKey:DOWNLOAD_OBJ] mutableCopy];
if (arrayDownloding==nil)
{
arrayDownloding=[[NSMutableArray alloc]init];
}
[arrayDownloding addObject:dictInfo];
[[NSUserDefaults standardUserDefaults] setObject:arrayDownloding forKey:DOWNLOAD_OBJ];
[[NSUserDefaults standardUserDefaults] synchronize];
[self addDownloadTask:fileName andFilePath:filePath andFileDestPath:fileDestination];
[self.tblDownloading reloadData];
[self updateDownloadingTabBadge];
}
-(void)addDownloadTask:(NSString *)fileName andFilePath:(NSString*)filePath andFileDestPath:(NSString*)fileDestPath
{
dispatch_async(dispatch_get_main_queue(), ^{ //go back to the main thread (not necessary)
NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
NSLog(#"URL :%#", filePath);
BOOL resume = YES;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:filePath]];
//customize the request if needed... Example:
[request setTimeoutInterval:90.0];
//start downloading the video to the temporary directory
JGDownloadOperation *operation = [[JGDownloadOperation alloc] initWithRequest:request destinationPath:file allowResume:resume];
operation.name=fileDestPath;
[operation setMaximumNumberOfConnections:6];
[operation setRetryCount:3];
__block CFTimeInterval started;
[operation setCompletionBlockWithSuccess:^(JGDownloadOperation *operation)
{
double kbLength = (double)operation.contentLength/1024.0f;
CFTimeInterval delta = CFAbsoluteTimeGetCurrent()-started;
NSLog(#"Success! Downloading %.2f MB took %.1f seconds, average Speed: %.2f kb/s", kbLength/1024.0f, delta, kbLength/delta);
NSPredicate *pred=[NSPredicate predicateWithFormat:#"fileName == %#",[operation.destinationPath lastPathComponent]];
NSArray *arrayFilter=[[self.ArrayDownloading filteredArrayUsingPredicate:pred] mutableCopy];
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath:[[arrayFilter objectAtIndex:0]valueForKey:kDownloadKeyFilePath]])
{
[fileManager removeItemAtPath:[[arrayFilter objectAtIndex:0] valueForKey:kDownloadKeyFilePath] error:NULL];
}
unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:operation.destinationPath error:nil] fileSize];
NSNumber *number=[[arrayFilter objectAtIndex:0] valueForKey:kDownloadKeyFileSize];
unsigned long long DictfileSize =[number unsignedLongLongValue];
if (fileSize==DictfileSize)
{
BOOL isWrite = [fileManager moveItemAtPath:operation.destinationPath toPath:[[arrayFilter objectAtIndex:0] valueForKey:kDownloadKeyFilePath] error:NULL];
if (isWrite)
{
NSInteger index = [self.ArrayDownloading indexOfObject:[arrayFilter objectAtIndex:0]];
[self.ArrayDownloading removeObjectAtIndex:index];
NSMutableArray *arrayDownloding=[[[NSUserDefaults standardUserDefaults] objectForKey:DOWNLOAD_OBJ] mutableCopy];
NSArray *ArrayFilter=[arrayDownloding filteredArrayUsingPredicate:pred];
if (ArrayFilter.count>0)
{
[arrayDownloding removeObject:[ArrayFilter objectAtIndex:0]];
[[NSUserDefaults standardUserDefaults] setObject:arrayDownloding forKey:DOWNLOAD_OBJ];
[[NSUserDefaults standardUserDefaults] synchronize];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self presentNotificationForDownload];
[self updateDownloadingTabBadge];
[self.tblDownloading reloadData];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[[[UIAlertView alloc]initWithTitle:nil message:#"Can`t Write File At Path." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil] show];
});
}
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *actionControllerDelete = [UIAlertController
alertControllerWithTitle:#"Options"
message:#"The File Was currupted."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"Retry"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
NSMutableDictionary *dict=[[arrayFilter objectAtIndex:0] mutableCopy];
[self addDownloadTask:[dict valueForKey:kDownloadKeyFileName] andFilePath:[dict valueForKey:kDownloadKeyURL] andFileDestPath:[dict valueForKey:kDownloadKeyFilePath]];
}];
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:#"Delete"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[operation cancelAndClearFiles];
[self.ArrayDownloading removeObject:[[arrayFilter objectAtIndex:0] mutableCopy]];
[[NSUserDefaults standardUserDefaults] setObject:self.ArrayDownloading forKey:DOWNLOAD_OBJ];
[[NSUserDefaults standardUserDefaults] synchronize];
[self.tblDownloading reloadData];
[actionControllerDelete dismissViewControllerAnimated:YES completion:nil];
}];
[actionControllerDelete addAction:ok];
[actionControllerDelete addAction:cancel];
[self presentViewController:actionControllerDelete animated:YES completion:nil];
});
}
}
failure:^(JGDownloadOperation *operation, NSError *error)
{
NSLog(#"Operation Failed: %#", error.localizedDescription);
UIApplication *application = [UIApplication sharedApplication];
UIApplicationState appCurrentState = [application applicationState];
if(appCurrentState == UIApplicationStateBackground)
{
if ([error.localizedDescription isEqualToString:#"The Download was Cancelled"]||[error.localizedDescription isEqualToString:#"The request timed out."]||[error.localizedDescription isEqualToString:#"The network connection was lost."])
{
NSPredicate *pred=[NSPredicate predicateWithFormat:#"fileName == %#",[operation.destinationPath lastPathComponent]];
NSArray *arrayFilter=[[self.ArrayDownloading filteredArrayUsingPredicate:pred] mutableCopy];
NSMutableDictionary *dict=[[arrayFilter objectAtIndex:0] mutableCopy];
[self addDownloadTask:[dict valueForKey:kDownloadKeyFileName] andFilePath:[dict valueForKey:kDownloadKeyURL] andFileDestPath:[dict valueForKey:kDownloadKeyFilePath]];
}
}
else
{
if ([error.localizedDescription isEqualToString:#"The request timed out."]||[error.localizedDescription isEqualToString:#"The network connection was lost."])
{
dispatch_async(dispatch_get_main_queue(), ^{
[[[UIAlertView alloc]initWithTitle:#"UltraFast DL" message:#"network connection was lost." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil] show];
NSPredicate *pred=[NSPredicate predicateWithFormat:#"fileName == %#",[operation.destinationPath lastPathComponent]];
NSArray *arrayFilter=[[self.ArrayDownloading filteredArrayUsingPredicate:pred] mutableCopy];
NSMutableDictionary *dict=[[arrayFilter objectAtIndex:0] mutableCopy];
[dict setObject:RequestStatusPaused forKey:kDownloadKeyStatus];
NSInteger index =[self.ArrayDownloading indexOfObject:[arrayFilter objectAtIndex:0]];
[self.ArrayDownloading replaceObjectAtIndex:index withObject:dict];
[[NSUserDefaults standardUserDefaults] setObject:self.ArrayDownloading forKey:DOWNLOAD_OBJ];
[[NSUserDefaults standardUserDefaults] synchronize];
[self.tblDownloading reloadData];
});
}
else if ([error.localizedDescription isEqualToString:#"unsupported URL"])
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *actionControllerDelete = [UIAlertController
alertControllerWithTitle:#"Options"
message:#"The download has been Paused for too long and a connection to the video has been lost."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSPredicate *pred=[NSPredicate predicateWithFormat:#"fileName == %#",[operation.destinationPath lastPathComponent]];
NSArray *arrayFilter=[[self.ArrayDownloading filteredArrayUsingPredicate:pred] mutableCopy];
NSMutableDictionary *dict=[[arrayFilter objectAtIndex:0] mutableCopy];
[dict setObject:RequestStatusPaused forKey:kDownloadKeyStatus];
NSInteger index =[self.ArrayDownloading indexOfObject:[arrayFilter objectAtIndex:0]];
[self.ArrayDownloading replaceObjectAtIndex:index withObject:dict];
[[NSUserDefaults standardUserDefaults] setObject:self.ArrayDownloading forKey:DOWNLOAD_OBJ];
[[NSUserDefaults standardUserDefaults] synchronize];
[self.tblDownloading reloadData];
[actionControllerDelete dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:#"Delete"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[operation cancelAndClearFiles];
NSPredicate *pred=[NSPredicate predicateWithFormat:#"fileName == %#",[operation.destinationPath lastPathComponent]];
NSArray *arrayFilter=[[self.ArrayDownloading filteredArrayUsingPredicate:pred] mutableCopy];
[self.ArrayDownloading removeObject:[[arrayFilter objectAtIndex:0] mutableCopy]];
[[NSUserDefaults standardUserDefaults] setObject:self.ArrayDownloading forKey:DOWNLOAD_OBJ];
[[NSUserDefaults standardUserDefaults] synchronize];
[self.tblDownloading reloadData];
[actionControllerDelete dismissViewControllerAnimated:YES completion:nil];
}];
[actionControllerDelete addAction:ok];
[actionControllerDelete addAction:cancel];
[self presentViewController:actionControllerDelete animated:YES completion:nil];
});
}
else if (![error.localizedDescription isEqualToString:#"The Download was Cancelled"])
{
dispatch_async(dispatch_get_main_queue(), ^{
NSPredicate *pred=[NSPredicate predicateWithFormat:#"fileName == %#",[operation.destinationPath lastPathComponent]];
NSArray *arrayFilter=[[self.ArrayDownloading filteredArrayUsingPredicate:pred] mutableCopy];
NSMutableDictionary *dict=[[arrayFilter objectAtIndex:0] mutableCopy];
[dict setObject:RequestStatusPaused forKey:kDownloadKeyStatus];
NSInteger index =[self.ArrayDownloading indexOfObject:[arrayFilter objectAtIndex:0]];
[self.ArrayDownloading replaceObjectAtIndex:index withObject:dict];
[[NSUserDefaults standardUserDefaults] setObject:self.ArrayDownloading forKey:DOWNLOAD_OBJ];
[[NSUserDefaults standardUserDefaults] synchronize];
[self.tblDownloading reloadData];
});
}
}
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, unsigned long long totalBytesReadThisSession, unsigned long long totalBytesWritten, unsigned long long totalBytesExpectedToRead, NSUInteger tag)
{
CFTimeInterval delta = CFAbsoluteTimeGetCurrent()-started;
NSLog(#"Progress: %.2f%% Average Speed: %.2f kB/s Tag:%lu File:%#", ((double)totalBytesWritten/(double)totalBytesExpectedToRead)*100.0f, totalBytesReadThisSession/1024.0f/delta,(unsigned long)tag,fileName);
dispatch_async(dispatch_get_main_queue(), ^{
NSPredicate *pred=[NSPredicate predicateWithFormat:#"fileName == %#",fileName];
NSArray *arrayFilter=[[self.ArrayDownloading filteredArrayUsingPredicate:pred] mutableCopy];
if (arrayFilter.count>0)
{
NSInteger index=[self.ArrayDownloading indexOfObject:[arrayFilter objectAtIndex:0]];
NSMutableDictionary *dict=[[arrayFilter objectAtIndex:0] mutableCopy];
double progress =((double)totalBytesWritten/(double)totalBytesExpectedToRead)*100.0f;
double speed=totalBytesReadThisSession/1024.0f/delta;
NSString *fileSizeInUnits = [NSString stringWithFormat:#"%.1f %#",
[Utility calculateFileSizeInUnit:(unsigned long long)totalBytesExpectedToRead],
[Utility calculateUnit:(unsigned long long)totalBytesExpectedToRead]];
NSMutableString *detailLabelText=[NSMutableString stringWithFormat:#"(%.1f%#/%#) Folder:%#",[Utility calculateFileSizeInUnit:(unsigned long long)totalBytesWritten],[Utility calculateUnit:(unsigned long long)totalBytesWritten],fileSizeInUnits,[dict valueForKey:kDownloadKeyFolderName]];
[dict setObject:[NSString stringWithFormat:#"%#",detailLabelText] forKey:kDownloadKeyDetails];
Cell *cell =(Cell*)[self.tblDownloading cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
[cell.progessView setProgress:progress/100];
[dict setObject:[NSString stringWithFormat:#" %.2f%%",progress/100] forKey:kDownloadKeyProgress];
[dict setObject:[NSNumber numberWithUnsignedLongLong:totalBytesExpectedToRead] forKeyedSubscript:kDownloadKeyFileSize];
[self.ArrayDownloading replaceObjectAtIndex:index withObject:dict];
[[NSUserDefaults standardUserDefaults] setObject:self.ArrayDownloading forKey:DOWNLOAD_OBJ];
[[NSUserDefaults standardUserDefaults] synchronize];
NSString *speedDetail=[NSString stringWithFormat:#"%.0f kB/s",ceil(speed)];
[cell.lblSpeed setText:speedDetail];
[cell.lblDetail setText:detailLabelText];
}
});
}];
[operation setOperationStartedBlock:^(NSUInteger tag, unsigned long long totalBytesExpectedToRead)
{
started = CFAbsoluteTimeGetCurrent();
NSLog(#"Operation Started, JGDownloadAcceleration version %#", kJGDownloadAccelerationVersion);
}];
if (!q)
{
q = [[JGOperationQueue alloc] init];
q.handleNetworkActivityIndicator = YES;
q.handleBackgroundTask = YES;
}
[q addOperation:operation];
});
}
As I tested it, it is working in background as of now but is it fine that this will approved on App Store as it does not use NSURLSession for background download and as I know only NSURLSession is working fine with background downloading tasks.
Please guide me or point me out in right direction. Any help will be appreciated.

UIAlertview error: Unable to simultaneously satisfy constraints

This question has been asked many times, but I have tried all of the options, and none of them seem to work. In my ios app, whenever I try to make an alert view, this happens:
http://i61.tinypic.com/kalnk2.png
I don't know what to do. When I click ok, I get this error: (This is the entire error)
http://pastebin.com/raw.php?i=BEeGbjJ8
My code is:
#implementation AJSettingsViewController
-(NSString*) dataFilePath{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:FILENAME];
}
-(void) saveFile{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:country];
[array addObject:state];
[array addObject:town];
[array addObject:zipcode];
[array addObject:name];
[array writeToFile:[self dataFilePath] atomically:YES];
//[array dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
zipcodetextfield.translatesAutoresizingMaskIntoConstraints = NO;
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)zipcodelookup:(id)sender{
[zipcodetextfield resignFirstResponder];
zipcodetextfield.translatesAutoresizingMaskIntoConstraints = NO;
zipcode = zipcodetextfield.text;
if(zipcode.length >0){
NSString *url = [NSString stringWithFormat:#"http://ziptasticapi.com/%#",zipcode];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString: url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[connection start];
NSError *noconnection;
NSString *htmlpage = [NSString stringWithContentsOfURL:[NSURL URLWithString: url] encoding:NSASCIIStringEncoding
error:&noconnection];
//NSLog(htmlpage);
if ([htmlpage rangeOfString:#"error"].location == NSNotFound) {
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"{" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"}" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#":" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"\"" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"country" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"city" withString:#""];
htmlpage = [htmlpage stringByReplacingOccurrencesOfString:#"state" withString:#""];
NSLog(htmlpage);
} else {
zipcodetextfield.text = #"";
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"We were unable to locate this zipcode. Please try again"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
message.translatesAutoresizingMaskIntoConstraints = NO;
[message show];
}
}else{
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please Enter A ZipCode"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
message.translatesAutoresizingMaskIntoConstraints = NO;
[message show];
}
}
-(IBAction)exitkeyboard:(id)sender{
[zipcodetextfield resignFirstResponder];
}
#end
I am at absolute wits end here, so any help would be greatly appreciated.
Thanks
message.translatesAutoresizingMaskIntoConstraints = NO;
Do not set this for UIAlertView - the alert view and its private manager will decide how its layout works.
Try to use delegate:self instead of nil and in your .h file, add UIAlertViewDelegate so that it looks like this:
#interface AJSettingsViewController : UIViewController <UIAlertViewDelegate>
Try to use UIAlertController:
UIAlertController *myAlertController = [UIAlertController
alertControllerWithTitle:#"Title"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
with buttons:
UIAlertAction *myCancelAction = [UIAlertAction
actionWithTitle:NSLocalizedString(#"Cancel", #"Cancel")
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
NSLog(#"Cancel action");
[self someGreatActionWithIndex:0];
}];
UIAlertAction *myOkAction = [UIAlertAction
actionWithTitle:NSLocalizedString(#"OK", #"OK")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(#"OK action");
[self someGreatActionWithIndex:1];
}];
[myAlertController addAction:myCancelAction];
[myAlertController addAction:myOkAction];
Hope this helps!

Showing UIActivityIndicator when calling a webservice

I need to show a UIActivityIndicator while i am waiting for response from the web service. Where exactly do i put the code for it?? It does not work this way. the activity indicator does not show up.
Do i need to use asynchronous request in order to show it??
-(void)callWebService
{
[self.customercareSearchbar resignFirstResponder];
[self.SRResultDictionary removeAllObjects];
NSLog(#"web service called");
NSString *srn = _SRNumber;
NSString *serviceURL = [NSString stringWithFormat:#"https://abcdef...];
#try {
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:activity];
activity.center = self.view.center;
[self.view bringSubviewToFront:loadView];
activity.hidesWhenStopped = YES;
[activity setHidden:NO];
[activity startAnimating];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
[activity stopAnimating];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
else
{
NSLog(#"parsed");
NSLog(#"parsed.. the size is %lu", (unsigned long)[parsedData count]);
NSLog(#"%#", parsedData);
NSString *status = [parsedData objectForKey:#"ns:Status"];
NSLog(#"the status is %#", status);
if([status isEqualToString:#"Success"])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:#"SwitchState"] isEqualToString:#"OFF"])
{
//do nothing
}
else
{
[self saveNumberInDatabase:srn];
}
NSMutableDictionary *third = [parsedData objectForKey:#"ListOfXrxLvServiceRequest"];
NSLog(#"internal dict is %#", third);
self.SRResultDictionary = [third objectForKey:#"ServiceRequest"];
[self.customerCareTableView reloadData];
[self.customerCareTableView setHidden:NO];
}
else if([status isEqualToString:#"Record Not Found"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Invalid Entry" message:#"Please enter a valid Service Request Number" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Problem in Network. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
}
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NULL message:#"Problem In Network Connection. Please Try Again!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[self.customerCareTableView setHidden:YES];
}
#finally {
}
}
Yes, problem is the Synchronous request.
If it is fine to send ASynchronous request then try doing this.
[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// stop activity
// write other code you want to execute
}];
I found MBProgressHUD is best indicator and you can use is simply in your starting of method call like
dispatch_async(dispatch_get_main_queue(), ^{
if(!HUD) HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.view addSubview:HUD];
HUD.delegate = self;
HUD.userInteractionEnabled = NO;
HUD.labelText = #"Saving your Preferences...";
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
[HUD show:YES];
});
and in your finally block you can hide this like
dispatch_async(dispatch_get_main_queue(), ^{
[HUD hide:YES];
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
});
//.h file
#interface ViewController : UIViewController
{
UIActivityIndicatorView *activityIndicator;
BOOL showingActivityIndicator;
}
#property(nonatomic) BOOL showingActivityIndicator;
#property(nonatomic) UIActivityIndicatorView *activityIndicator;
#end
//.m file
#synthesize showingActivityIndicator,activityIndicator;
///// Call this method in viewDidLoad
-(void)initializeClass
{
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.activityIndicator.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
self.activityIndicator.hidesWhenStopped = YES;
[self layoutSubviews];
}
-(void)layoutSubviews
{
CGRect activityIndicatorFrame = self.activityIndicator.frame;
activityIndicatorFrame.origin.x = (self.view.frame.size.width - self.activityIndicator.frame.size.width) / 2;
activityIndicatorFrame.origin.y = (self.view.frame.size.height - self.activityIndicator.frame.size.height) / 2;
self.activityIndicator.frame = activityIndicatorFrame;
[self.view addSubview:self.activityIndicator];
}
-(void)setShowingActivityIndicator:(BOOL)showingActivityIndicators
{
if (showingActivityIndicators) {
[self.activityIndicator startAnimating];
} else {
[self.activityIndicator stopAnimating];
}
showingActivityIndicator= showingActivityIndicators;
}
-(void)dummyButtonAction // you button action to call service
{
[self setShowingActivityIndicator:YES];
[self performSelector:#selector(callWebService) withObject:nil afterDelay:0.3];
// [self callWebService];
}
-(void)callWebService
{
[self.view endEditing:YES]; // this statement will make sure keyboard is resigned
//[self.SRResultDictionary removeAllObjects];
NSLog(#"web service called");
NSString *srn = _SRNumber;
NSString *serviceURL = [NSString stringWithFormat:#"https://abcdef...];
#try {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:serviceURL]];
NSURLResponse *serviceResponse = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&serviceResponse error:&err];
NSMutableDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&err];
if(!parsedData)
{
NSLog(#"data not parsed");
[self ShowAlertViewWithTitleString:#"ERROR":#"Problem in Network. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
else
{
NSLog(#"parsed");
NSLog(#"parsed.. the size is %lu", (unsigned long)[parsedData count]);
NSLog(#"%#", parsedData);
NSString *status = [parsedData objectForKey:#"ns:Status"];
NSLog(#"the status is %#", status);
if([status isEqualToString:#"Success"])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:#"SwitchState"] isEqualToString:#"OFF"])
{
//do nothing
}
else
{
[self saveNumberInDatabase:srn];
}
NSMutableDictionary *third = [parsedData objectForKey:#"ListOfXrxLvServiceRequest"];
NSLog(#"internal dict is %#", third);
self.SRResultDictionary = [third objectForKey:#"ServiceRequest"];
[self.customerCareTableView reloadData];
[self.customerCareTableView setHidden:NO];
}
else if([status isEqualToString:#"Record Not Found"])
{
[self ShowAlertViewWithTitleString:#"Invalid Entry":#"Please enter a valid Service Request Number"];
[self.customerCareTableView setHidden:YES];
}
else
{
[self ShowAlertViewWithTitleString:#"ERROR":#"Problem in Network. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
}
}
#catch (NSException *exception)
{
[self ShowAlertViewWithTitleString:#"":#"Problem In Network Connection. Please Try Again!"];
[self.customerCareTableView setHidden:YES];
}
#finally {
}
[self setShowingActivityIndicator:NO];
}
- (void)ShowAlertViewWithTitleString :(NSString *)title :(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}

UITableView loading and reloading

I have trouble loading a UITableView with multiple sections. In order to fill it I use a function (fetches feed from Twitter). At the moment the view loads, the function returns NULL values for it's fields, but after a few seconds it returns the desired feed.
However, before the desired feed is returned, the fields in my tableView are shown to be NULL and then they refresh and are filled properly (No NULL values).
My question is, How can I make the tableView cells not load until the feed is properly loaded?
I have the same problem with my Facebook feed, however it crashes because it doesn't even return any of the values.
in ViewDidLoad I have put
[self getTwitterFeed:^() {
[self.tableView reloadData];
}];
EDIT here is the code of the method
- (void)getTwitterFeed:(void (^)(void))completion {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
#try
{
if ([[[NSUserDefaults standardUserDefaults] objectForKey:#"TwitterLoggedIn"] isEqualToString:#"YES"]) {
[account requestAccessToAccountsWithType:accountType
options:nil completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
NSArray *arrayOfAccounts = [account
accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts objectAtIndex:[[NSUserDefaults standardUserDefaults] integerForKey:#"TwitterAccountNumber" ]];
NSURL *requestURL = [NSURL URLWithString:#"http://api.twitter.com/1.1/statuses/home_timeline.json"];
NSMutableDictionary *parameters =
[[NSMutableDictionary alloc] init];
[parameters setObject:#"35" forKey:#"count"];
[parameters setObject:#"true" forKey:#"include_entities"];
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:requestURL parameters:parameters];
postRequest.account = twitterAccount;
[postRequest performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse
*urlResponse, NSError *error)
{
self.dataSource = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&error];
if (self.dataSource.count != 0) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Description %#",_dataSource);
for(int i=0;i<[_dataSource count];i++)
{
NSMutableString *url = [NSMutableString stringWithFormat: #"https://www.twitter.com/%#/status/%#",[[[_dataSource objectAtIndex:i ]objectForKey:#"user"] valueForKey:#"screen_name"],[[_dataSource objectAtIndex:i ]objectForKey:#"id"]];
[tweetURL addObject:url];
NSMutableString *urlApp = [NSMutableString stringWithFormat: #"twitter://user?screen_name=%#?status?id=%#",[[[_dataSource objectAtIndex:i ]objectForKey:#"user"] valueForKey:#"screen_name"],[[_dataSource objectAtIndex:i ]objectForKey:#"id"]];
[tweetAppURL addObject:urlApp];
}
CGRect frame = CGRectMake (120, 120, 80, 80);
activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame: frame];
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
activityIndicator.color = [UIColor whiteColor];
[activityIndicator startAnimating];
activityIndicator.hidesWhenStopped=YES;
[self.view addSubview:activityIndicator];
completion();
//[self.tableView reloadData];
});
}
}];
}
} else {
}
}];
}
else //IF FEED IS NOT TURNED ON
{
[self.tableView reloadData];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Your TWITTER feed is either turned of or isn't initiated!" message:#"Please enable it in Settings" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
}
Try something like this
- (void)viewDidLoad
{
[super viewDidLoad];
// Do something perhaps
// Do any additional setup after loading the view, typically from a nib.
[self getTwitterFeed:^() { // Completion block
dispatch_async(dispatch_get_main_queue(), ^{
[myTableView reloadData];
});
}];
}
- (void)getTwitterFeed:(void (^)(void))completion {
// Get the feed and call:
NSLog(#"We finished receiving the data");
completion();
}
And to show the correct number of rows (need to be edited according to # sections)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (self.myFeedArray.count == 0 ? 0 : self.myFeedArray.count);
}
Loading cells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(myFeedArray.count == 0) { // no feeds yet
NSLog(#"The count in the table is 0");
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.text = #"Updating...";
[cell.textLabel setTextAlignment:NSTextAlignmentCenter];
[cell.textLabel setAlpha:0.5];
cell.userInteractionEnabled = NO;
return cell;
}
//else do stuff
}
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSData * data=[NSData dataWithContentsOfURL:[NSURL URLWithString:URLForPayload]];
[self performSelectorOnMainThread:#selector(fetchCompleted:) withObject:data waitUntilDone:YES];
});
}
-(void) fetchCompleted:(NSData *)responseData
{
// Complete data available now reload TableView
}

Resources