Table View is not displaying Data - ios

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 -

Related

iOS auto-renew subscription receipt validation issue

Apple rejects my iOS app due to the following reason:
2.1 After purchasing the In App Purchase, the App Store authenticated and confirmed, but the app failed to validate the receipt.
I did not experience that while I am testing the app in sandbox environment. I successfully disable ads on purchase - here is a sample video when I made a purchase on iPad and after that restore it on iPhone:
https://photos.app.goo.gl/jeH1gtSKroF7QjVCA
I am handling all purchases in my IAPManager class - full code below:
//
// IAPManager.m
// Sudoku
//
// Created by szulcu on 03/06/2019.
// Copyright © 2019 AliorBank. All rights reserved.
//
#import "IAPManager.h"
#import "Utils.h"
#interface IAPManager() <SKProductsRequestDelegate, SKPaymentTransactionObserver>
#property(strong, nonatomic) SKProductsRequest *productsRequest;
#property(strong, nonatomic) NSArray<SKProduct*> *validProducts;
#property(nonatomic, assign) long long validPurchaseMs;
#property(strong, nonatomic) NSTimer *timer;
#end
#implementation IAPManager
+ (instancetype)sharedInstance
{
static IAPManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[IAPManager alloc] init];
sharedInstance.validPurchaseMs = -1;
});
return sharedInstance;
}
- (void)restorePurchase
{
[SKPaymentQueue.defaultQueue restoreCompletedTransactions];
}
- (void)addTransactionObserver{
[SKPaymentQueue.defaultQueue addTransactionObserver:self];
}
- (void)removeTransactionObserver{
[SKPaymentQueue.defaultQueue removeTransactionObserver:self];
}
- (void)fetchAvailableProducts
{
NSSet *productIdentifiers = [NSSet setWithArray:_productIdentifiers];
_productsRequest = [[SKProductsRequest alloc]
initWithProductIdentifiers:productIdentifiers];
_productsRequest.delegate = self;
[_productsRequest start];
}
- (BOOL)canMakePurchases
{
return [SKPaymentQueue canMakePayments];
}
- (void)purchaseMyProduct:(SKProduct*)product
{
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
#pragma mark StoreKit Delegate
-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for (SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchasing:
NSLog(#"Purchasing");
break;
case SKPaymentTransactionStatePurchased:
NSLog(#"Purchased ");
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
if(self.delegate != nil)
{
if([self.delegate respondsToSelector:#selector(productWithIdentifier:valid:)])
{
[self.delegate productWithIdentifier:transaction.payment.productIdentifier valid:[self checkInAppPurchaseStatus]];
}
}
break;
case SKPaymentTransactionStateRestored:
NSLog(#"Restored ");
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
if(self.delegate != nil)
{
if([self.delegate respondsToSelector:#selector(productWithIdentifier:valid:)])
{
[self.delegate productWithIdentifier:transaction.payment.productIdentifier valid:[self checkInAppPurchaseStatus]];
}
}
break;
case SKPaymentTransactionStateFailed:
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
NSLog(#"Purchase failed ");
break;
default:
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
}
if(self.delegate != nil)
{
if([self.delegate respondsToSelector:#selector(transactionStateChanged:)])
{
[self.delegate transactionStateChanged:transaction.transactionState];
}
}
}
}
-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
if ([response.products count] > 0) {
_validProducts = response.products;
}
}
- (BOOL)hasProducts
{
return _validProducts !=nil;
}
- (void)showPurchaseDialogInViewController:(UIViewController*) viewController completion:(void (^)(NSString*)) completion
{
if([self canMakePurchases] == NO)
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(#"iap_warning", nil) message:NSLocalizedString(#"iap_disabled_msg", nil) preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(#"dialogNewGameOk", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completion(IAP_DIALOG_COMPLETION_CANCEL);
}];
[alertController addAction:cancel];
[viewController presentViewController:alertController animated:YES completion:nil];
}
else if(self.hasProducts)
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(#"iap_purchase", nil) message:#"\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
weakify(self)
CGFloat margin = 8;
int textViewWidth = alertController.view.bounds.size.width - margin*4;
if ([Utils isIpad]) {
textViewWidth = 304 - margin*2;
}
UITextView *linkTextView = [[UITextView alloc] initWithFrame:CGRectMake(margin, margin*4, textViewWidth+100, 60)];
linkTextView.text = NSLocalizedString(#"iap_select_subscription_link", nil);
linkTextView.backgroundColor = UIColor.clearColor;
linkTextView.scrollEnabled = NO;
linkTextView.dataDetectorTypes = UIDataDetectorTypeLink;
linkTextView.editable = NO;
[alertController.view addSubview:linkTextView];
UITextView *descriptionTextView = [[UITextView alloc] initWithFrame:CGRectMake(margin, margin*4 + 60, textViewWidth, 120)];
descriptionTextView.text = NSLocalizedString(#"iap_select_subscription", nil);
descriptionTextView.backgroundColor = UIColor.clearColor;
descriptionTextView.scrollEnabled = YES;
descriptionTextView.showsVerticalScrollIndicator = YES;
descriptionTextView.dataDetectorTypes = UIDataDetectorTypeLink;
descriptionTextView.editable = NO;
[alertController.view addSubview:descriptionTextView];
///
for(SKProduct *product in _validProducts)
{
UIAlertAction *action = [UIAlertAction actionWithTitle:[NSString stringWithFormat:#"%# - %#", product.localizedTitle, product.localizedDescription] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[weak_self purchaseMyProduct:product];
completion(IAP_DIALOG_COMPLETION_PURCHASED);
}];
[alertController addAction:action];
}
UIAlertAction *restore = [UIAlertAction actionWithTitle:NSLocalizedString(#"iap_restore_purchase", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[weak_self restorePurchase];
completion(IAP_DIALOG_COMPLETION_RESTORED);
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(#"dialogNewGameCancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completion(IAP_DIALOG_COMPLETION_CANCEL);
}];
[alertController addAction:restore];
[alertController addAction:cancel];
[alertController.popoverPresentationController setPermittedArrowDirections:0];
CGRect rect = viewController.view.frame;
rect.origin.x = viewController.view.frame.size.width/20;
rect.origin.y = viewController.view.frame.size.height/20;
alertController.popoverPresentationController.sourceView = viewController.view;
alertController.popoverPresentationController.sourceRect = rect;
[viewController presentViewController:alertController animated:YES completion:nil];
}
else
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(#"iap_warning", nil) message:NSLocalizedString(#"iap_no_products_warning", nil) preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *ok = [UIAlertAction actionWithTitle:NSLocalizedString(#"dialogNewGameOk", nil) style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:ok];
[viewController presentViewController:alertController animated:YES completion:nil];
}
}
- (BOOL)checkInAppPurchaseStatus
{
if(self.validPurchaseMs > 0)
{
return YES;
}
// Load the receipt from the app bundle.
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];
if (receipt) {
BOOL sandbox = [[receiptURL lastPathComponent] isEqualToString:#"sandboxReceipt"];
// Create the JSON object that describes the request
NSError *error;
NSDictionary *requestContents = #{
#"receipt-data": [receipt base64EncodedStringWithOptions:0], #"password":IAP_SHARED_SECRET, #"exclude-old-transactions" : #YES
};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents
options:0
error:&error];
if (requestData) {
// Create a POST request with the receipt data.
NSURL *storeURL = [NSURL URLWithString:#"https://buy.itunes.apple.com/verifyReceipt"];
if (sandbox) {
storeURL = [NSURL URLWithString:#"https://sandbox.itunes.apple.com/verifyReceipt"];
}
NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:storeURL];
[storeRequest setHTTPMethod:#"POST"];
[storeRequest setHTTPBody:requestData];
BOOL validPurchase = NO;
//Can use sendAsynchronousRequest to request to Apple API, here I use sendSynchronousRequest
NSError *error;
NSURLResponse *response;
NSData *resData = [self sendSynchronousRequest:storeRequest returningResponse:&response error:&error];
if (error) {
validPurchase = NO;
}
else
{
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:resData options:0 error:&error];
if (!jsonResponse) {
validPurchase = NO;
}
else
{
NSLog(#"jsonResponse:%#", jsonResponse);
NSArray *latestReceiptsInfo = jsonResponse[#"latest_receipt_info"];
long long expirationDateMs = [[latestReceiptsInfo valueForKeyPath:#"#max.expires_date_ms"] longLongValue];
long long requestDateMs = [jsonResponse[#"receipt"][#"request_date_ms"] longLongValue];
NSLog(#"%lld--%lld", expirationDateMs, requestDateMs);
validPurchase = [[jsonResponse objectForKey:#"status"] integerValue] == 0 && (expirationDateMs > requestDateMs);
self.validPurchaseMs = expirationDateMs - requestDateMs;
if(self.validPurchaseMs > 0)
{
weakify(self)
if (#available(iOS 10.0, *)) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
[weak_self timerAction];
}];
} else {
// Fallback on earlier versions
_timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(timerAction) userInfo:nil repeats:YES];
}
}
}
}
return validPurchase;
}
else
{
return NO;
}
}
else
{
return NO;
}
}
- (void)timerAction
{
self.validPurchaseMs -= 1000;
if(self.validPurchaseMs < 0)
{
[self.timer invalidate];
[self.delegate productWithIdentifier:#"" valid:NO];
}
}
- (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
{
NSError __block *err = NULL;
NSData __block *data;
BOOL __block reqProcessed = false;
NSURLResponse __block *resp;
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable _data, NSURLResponse * _Nullable _response, NSError * _Nullable _error) {
resp = _response;
err = _error;
data = _data;
reqProcessed = true;
}] resume];
while (!reqProcessed) {
[NSThread sleepForTimeInterval:0];
}
*response = resp;
*error = err;
return data;
}
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
for(SKPaymentTransaction *transaction in transactions){
NSLog(#"Transaction: %#", transaction);
}
}
// Sent when an error is encountered while adding transactions from the user's purchase history back to the queue.
- (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error{
}
// Sent when all transactions from the user's purchase history have successfully been added back to the queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue{
}
// Sent when the download state has changed.
- (void)paymentQueue:(SKPaymentQueue *)queue updatedDownloads:(NSArray<SKDownload *> *)downloads{
}
// Sent when a user initiates an IAP buy from the App Store
- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product{
return true;
}
- (void)paymentQueueDidChangeStorefront:(SKPaymentQueue *)queue{
}
#end
Please help understand what can possibly be wrong.
https://developer.apple.com/documentation/storekit/in-app_purchase/validating_receipts_with_the_app_store.
Warning
Do not call the App Store server verifyReceipt endpoint from your app. You can't build a trusted connection between a user’s device and the App Store directly, because you don’t control either end of that connection, which makes it susceptible to a man-in-the-middle attack.
I think this is the reason apple reject your app.

Upload image to web server

I want to upload UIImage to web site.I have implement some code.I have selected image from first page and upload on second page.where in this -----[body appendData:[NSData dataWithData:_imgData]];---- the _imgData becomes nil. enter code hereI have already written some code, but I don't know Where is my mistake.
My Code is:
-(void)ImgaeCropped:(UIImage *)image
{
_imageView.image=image;
Register2 *reg2=[self.storyboard instantiateViewControllerWithIdentifier:#"Register2"];
// reg2.self.selected_image=_imageView.image;
reg2.imgData=imageData;
picture_view.hidden=YES;
}
- (void)imagePickerController:(UIImagePickerController *) Picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
#try {
// transparent_view.hidden=YES;
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicator startAnimating];
indicator.frame=CGRectMake(0, 0, 10, 10);
indicator.center = CGPointMake(CGRectGetMidX(_imageView.bounds), CGRectGetMidY(_imageView.bounds));
[_imageView addSubview:indicator];
[indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[indicator setColor:[UIColor grayColor]];
[indicator startAnimating];
[self dismissViewControllerAnimated:YES completion:^ {
[indicator removeFromSuperview];
[indicator stopAnimating];
CropViewController *crop=[self.storyboard instantiateViewControllerWithIdentifier:#"CropViewController"];
crop.cropDelegate=self;
crop.image=[info objectForKey:UIImagePickerControllerOriginalImage];
// UIImageView *imgvUserImage = [[UIImageView alloc]init];
UIImage *imgvUserImage= [info objectForKey:UIImagePickerControllerOriginalImage];
imageData=UIImageJPEGRepresentation(imgvUserImage, 0.9);
[self presentViewController:crop animated:YES completion:nil];
}];
}
#catch (NSException *exception) {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Finish Picking" message:exception.description delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
}
#finally {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Finish Picking" message:#"Final" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
}
}
And the image selection code is ---------------
-(void)ImgaeCropped:(UIImage *)image
{
_imageView.image=image;
Register2 *reg2=[self.storyboard instantiateViewControllerWithIdentifier:#"Register2"];
// reg2.self.selected_image=_imageView.image;
reg2.imgData=imageData;
picture_view.hidden=YES;
}
- (void)imagePickerController:(UIImagePickerController *) Picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
#try {
// transparent_view.hidden=YES;
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicator startAnimating];
indicator.frame=CGRectMake(0, 0, 10, 10);
indicator.center = CGPointMake(CGRectGetMidX(_imageView.bounds), CGRectGetMidY(_imageView.bounds));
[_imageView addSubview:indicator];
[indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[indicator setColor:[UIColor grayColor]];
[indicator startAnimating];
[self dismissViewControllerAnimated:YES completion:^ {
[indicator removeFromSuperview];
[indicator stopAnimating];
CropViewController *crop=[self.storyboard instantiateViewControllerWithIdentifier:#"CropViewController"];
crop.cropDelegate=self;
crop.image=[info objectForKey:UIImagePickerControllerOriginalImage];
// UIImageView *imgvUserImage = [[UIImageView alloc]init];
UIImage *imgvUserImage= [info objectForKey:UIImagePickerControllerOriginalImage];
imageData=UIImageJPEGRepresentation(imgvUserImage, 0.9);
[self presentViewController:crop animated:YES completion:nil];
}];
}
#catch (NSException *exception) {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Finish Picking" message:exception.description delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
}
#finally {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Finish Picking" message:#"Final" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
}
}
add the AFNetworking to your project
https://github.com/AFNetworking/AFNetworking
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = #"Loading";
NSMutableDictionary* data=[NSMutableDictionary new];
//if you want to add parameters with the image
NSData *imageData = UIImageJPEGRepresentation(selectedImage, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = responseSerializer;
AFHTTPRequestOperation *op = [manager POST:#"http://www.pickkup.com/webservice/uploadpictureios.php" parameters:data constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"image" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
[hud hide:YES];
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[hud hide:YES];
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];

Share Extension is not showing data -- 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.

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