Xcode 7 build problems - ios

Has anybody experienced cloud storage issues when building to your device using Xcode 7? Interfacing with AWSS3 buckets works fine from my simulator, but doesn't actually work after building to my phone using Xcode 7 beta. It doesn't crash or anything, I just can't load data into my S3 bucket.
CODE BELOW. Feel free to just pick a single implementation (say, delete) and test it out. I have a free developer account and am only using Xcode 7 to build on my device.
viewController.h
#import <UIKit/UIKit.h>
#import <AWSS3/AWSS3.h>
#interface tableTableViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UIImageView *image;
- (IBAction)cameraRoll:(id)sender;
- (IBAction)editButton:(id)sender;
#property (strong, nonatomic) NSMutableArray *imageNames;
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) NSMutableArray *imageObjects;
#property (strong, nonatomic) AWSS3TransferManager *transferManager;
#end
ViewController.M
#interface UIViewController () {
}
#end
#implementation tableTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.transferManager = [AWSS3TransferManager defaultS3TransferManager];
self.view.backgroundColor = [UIColor whiteColor];
[self listAllObjects];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cameraRoll:(id)sender {
UIImagePickerController *iPhonePicker = [[UIImagePickerController alloc]init];
[iPhonePicker setDelegate:self];
//UIPopoverController *iPadPicker = [[UIPopoverController alloc]init];
UIImagePickerController *iPadPicker = [[UIImagePickerController alloc]init];
[iPadPicker setDelegate:self];
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone) {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
[iPhonePicker allowsEditing];
[iPhonePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
else {
[iPhonePicker setAllowsEditing:YES];
[iPhonePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
}
[self presentViewController:iPhonePicker animated:YES completion:nil];
}
// else if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad) {
// if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
// [iPadPicker setAllowsEditing:YES];
// [iPadPicker setSourceType:UIImagePickerControllerSourceTypeCamera];
// }
// else {
// [iPadPicker allowsEditing];
// [iPadPicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//CREATE POPOVER
// }
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self.image setImage:image];
[self uploadImage:info];
if ([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone) {
[self dismissViewControllerAnimated:YES completion:nil];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
-(void) uploadImage:(NSDictionary*)info {
imageObject *a = [imageObject new];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSString *imagePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"upload-image.tmp"];
NSData *imageData = UIImagePNGRepresentation(image);
NSString *fileName = [[NSString alloc] initWithFormat:#"%f.jpg", [[NSDate date] timeIntervalSince1970 ] ];
[imageData writeToFile:imagePath atomically:YES];
a.image = image;
a.key = fileName;
[self.imageObjects addObject:a];
AWSS3TransferManagerUploadRequest *uploadRequest = [AWSS3TransferManagerUploadRequest new];
uploadRequest.bucket = #"karanphotos";
uploadRequest.key = fileName;
uploadRequest.body = [NSURL fileURLWithPath:imagePath];
[[self.transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) {
if (task.error != nil) {
NSLog(#"%# is causing error", uploadRequest.key);
}
else {
NSLog(#"Upload successful");
}
return nil;
}];
}
-(void) listAllObjects {
AWSS3 *S3 = [AWSS3 defaultS3];
AWSS3ListObjectsRequest *listObjects = [AWSS3ListObjectsRequest new];
listObjects.bucket = #"karanphotos";
self.imageNames = [NSMutableArray new];
self.imageObjects = [NSMutableArray new];
[[S3 listObjects:listObjects]continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(#"listObjects failed-->%#", task.error);
}
else {
AWSS3ListObjectsOutput *output = task.result;
for (AWSS3Object *temp in output.contents) {
imageObject *a = [imageObject new];
a.key = temp.key;
[self.imageObjects addObject:a];
}
}
[self downloadImages:self.imageObjects];
return nil;
}];
}
-(void) downloadImages:(NSMutableArray *)imageNames {
for (imageObject *a in imageNames) {
NSString *downloadingFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"downloaded-%#", a.key]];
NSURL *url = [NSURL fileURLWithPath:downloadingFilePath];
AWSS3TransferManagerDownloadRequest *download = [AWSS3TransferManagerDownloadRequest new];
download.bucket = #"karanphotos";
download.key = a.key;
download.downloadingFileURL = url;
[[self.transferManager download:download] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) {
if (task.error) {
if ([task.error.domain isEqualToString:AWSS3TransferManagerErrorDomain]) {
switch (task.error.code) {
case AWSS3TransferManagerErrorCancelled:
case AWSS3TransferManagerErrorPaused:
break;
default:
NSLog(#"Error: %#", task.error);
break;
}
}
else {
NSLog(#"%#", task.error);
}
}
if (task.result) {
AWSS3TransferManagerDownloadOutput *downloadOutput = task.result;
NSLog(#"success");
UIImage *image = [[UIImage alloc]initWithData:[NSData dataWithContentsOfFile:downloadOutput.body]];
a.image = image;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
return nil;
}];
}
}
- (IBAction)editButton:(id)sender {
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
imageObject *a = [self.imageObjects objectAtIndex:indexPath.row];
self.image.image = a.image;
cell.textLabel.text = a.key;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
imageObject *a = [self.imageObjects objectAtIndex:indexPath.row];
self.image.image = a.image;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
imageObject *a = [self.imageObjects objectAtIndex:indexPath.row];
[self.imageObjects removeObject:a];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
AWSS3DeleteObjectRequest *deleteReqest = [AWSS3DeleteObjectRequest new];
deleteReqest.bucket = #"karanphotos";
deleteReqest.key = a.key;
[self deleteObjectFromBucket:deleteReqest];
} }
-(void)deleteObjectFromBucket:(AWSS3DeleteObjectRequest *)deleteRequest {
AWSS3 *s3 = [AWSS3 defaultS3];
[[s3 deleteObject:deleteRequest] continueWithBlock:^id(AWSTask *task) {
if(task.error){
if(task.error.code != AWSS3TransferManagerErrorCancelled && task.error.code != AWSS3TransferManagerErrorPaused){
NSLog(#"Error: [%#]", task.error);
}
}
else {
NSLog(#"Successfully deleted");
}
dispatch_async(dispatch_get_main_queue(), ^{
if (self.imageObjects.count == 0) {
[self.image setImage:nil];
[self.tableView reloadData];
}
});
return nil;
}];
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.imageObjects.count;
}
#end

Related

Textfields as search bar getting crash

I am using this code for textfiled as search bar.Here is my code. but i am getting crash for range on textfield.if i start entering then its crashing.Even not able to handle case sensitive text also
#import "ViewController.h"
#import "AFNetworking.h"
#import <QuartzCore/QuartzCore.h>
#interface ViewController ()
{
NSMutableArray *countryArray;
NSMutableArray *searchArray;
NSString *searchTextString;
BOOL isFilter;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_countryView.hidden = true;
self->countryArray = [[NSMutableArray alloc] init];
[self makeRestuarantsRequests];
_tableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
_tableView.layer.borderWidth = 1;
_tableView.layer.cornerRadius=5;
[self.searchTextField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self
name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - AFNetworking
-(void)makeRestuarantsRequests{
NSURL *url = [NSURL URLWithString:#"example url"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
self->countryArray = [responseObject objectForKey:#"data"];
[self.tableView reloadData];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
#pragma mark - Tableview Delegate and Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isFilter)
{
return [searchArray count];
}
else
return [countryArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *tempDictionary= [self->countryArray objectAtIndex:indexPath.row];
if(isFilter)
{
cell.textLabel.text=[searchArray objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = [tempDictionary objectForKey:#"name"];
}
// cell.textLabel.text = [tempDictionary objectForKey:#"name"];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[_SelectCountryButton setTitle:cell.textLabel.text forState:UIControlStateNormal];
_countryView.hidden = true;
}
-(void)textFieldDidChange:(UITextField *)textField
{
searchTextString=textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
for(NSString *string in countryArray){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
}
}
[self.tableView reloadData];}
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#pragma mark UITextFieldDelegates
- (IBAction)SelectCountry:(id)sender {
_countryView.hidden = false;
}
#end
Getting crash error :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI rangeOfString:options:]: unrecognized selector sent to instance 0x10128b4f0
error code :
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
for(NSString *string in countryArray){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
}
}
[self.tableView reloadData];}
}
Please help me out.How can i solve this issues.
Thanks in advance !
UPDATE :
{"response":true,"message":"country.","data":[{"id":1,"name":"Afghanistan"},{"id":2,"name":"Albania"},{"id":3,"name":"Algeria"},{"id":4,"name":"American Samoa"},{"id":5,"name":"Andorra"},{"id":6,"name":"Angola"}]}
well i have good approach with predicate
well according to you jsonResponse
// so forEach loop should like this
for(NSDictionary *Dic in CountryArray){
NSString*str=[NSString stringWithFormat:#"%#",[dic objectForKey:#"name"]];
}
// well i am not using for each loop instead of that i have nsmutablearray name as _searchArraySingle is same like your countryArray with predicate
// if you are using textfield in place of default Searchbar so use this then use NSPredicate
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(textFieldTextDidChangeOneCI:)
name:UITextFieldTextDidChangeNotification
object:searchTxt];
SearchBar.delegate = (id)self;
}
-(void)textFieldTextDidChangeOneCI:(NSNotification *)notification {
UITextField *textfield=[notification object];
[self predicatChangeText:textfield.text];
// NSLog(#"%#",textfield.text);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
-(void)predicatChangeText:(NSString*)text{
// myJSON.array
NSPredicate *predicateString = [NSPredicate predicateWithFormat:#"%K contains[cd] %#", #"name", text];
_filteredArray = [NSMutableArray arrayWithArray:[_searchArraySingle filteredArrayUsingPredicate:predicateString]];
NSLog(#"_filteredArray=%lu",(unsigned long)[_filteredArray count]);
[self.tableView reloadData];
}
- (IBAction)cancleSearch:(id)sender {
searchTxt.text=#"";
if (_filteredArray) {
_filteredArray=nil;
}
[self.searchTxt resignFirstResponder];
_filteredArray = myJSON.array;
[self.tableView reloadData];
}
Might this will help you out !!!! GoodLuck

How to resolve when UITableview is double open on same page

I have 2 UITableView. On first UITableView make for search and select cell. After selected cell from UITableView1. It's will show blank data of UITableView2 and show new UITableView2 again with data.
I'm sorry for my bad english language.
I can speak english a little bit.
If you don't understand my question.
Please follow to see pictures below here.
First UITableView: (Click button for go to second UITableView.)
After click button. UITableView2 show blank data.
And auto show new UITableView2 with data again.
UITableView1
#interface SearchByContainerDetailViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableViewWhereHoseList;
#end
#implementation SearchByContainerDetailViewController
#synthesize labelName,strName,txResult,strResult,labelStatus;
NSString *selectedWhereHouse;
GlobalVariable *gloablOnWherehouse;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
labelName.text = strName;
//txResult.text = strResult;
labelStatus.text = #"NULL";
gloablOnWherehouse = [GlobalVariable sharedInstance];
gloablOnWherehouse.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return (gloablOnWherehouse.arTableDataSelected)?[gloablOnWherehouse.arTableDataSelected count]:1;
}
- (NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"%lu", (unsigned long)[gloablOnWherehouse.arTableDataSelected count]);
return (gloablOnWherehouse.arTableDataSelected)?[gloablOnWherehouse.arTableDataSelected count]:1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SearchByContainerDetailViewCell";
SearchByContainerDetailViewCell *cell = [self.tableViewWhereHoseList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SearchByContainerDetailViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (gloablOnWherehouse.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:gloablOnWherehouse.arTableDataSelected];
if (myMutbleArray) {
NSDictionary *myDic = [gloablOnWherehouse.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_Detail"];
NSString *date = [self getString:[cont objectForKey:#"date"]];
NSString *qty = [self getString:[cont objectForKey:#"qty"]];
NSString *stock = [self getString:[cont objectForKey:#"stock"]];
NSString *ord = [self getString:[cont objectForKey:#"ord"]];
NSString *custmr = [self getString:[cont objectForKey:#"custmr"]];
NSString *remarks = [self getString:[cont objectForKey:#"remarks"]];
NSString *invoice = [self getString:[cont objectForKey:#"invoice"]];
NSString *due = [self getString:[cont objectForKey:#"due"]];
NSString *lot = [self getString:[cont objectForKey:#"lot"]];
NSString *gap = [self getString:[cont objectForKey:#"gap"]];
[cell setDate:date setQty:qty setStock:stock setOrd:ord setCustmr:custmr setRemarks:remarks setInvoice:invoice setDue:due setLot:lot setGap:gap];
}
}
}
return cell;
}
- (void) requestEWIServiceFinish:(EWIConnector *)connector responseData:(NSDictionary *)responseData{
NSLog(#"finish %#",connector.serviceName);
NSLog(#"response %#",responseData);
if ([connector.serviceName isEqualToString:#"special_selected_f10"])
{
NSLog(#"finish %#",connector.serviceName);
NSDictionary *content = responseData[#"content"];
NSString *stAlertMes = [content objectForKey:#"alertMessage"];
stAlertMes = [self getString:stAlertMes];
NSLog(#"AlertMSG : %#", stAlertMes);
if (![stAlertMes isEqualToString:#""]) {
NSLog(#"ALERT MESSAGE : %#", stAlertMes);
gloablOnWherehouse.arTableDataSelected = [[NSArray alloc] init];
}
else
{
NSLog(#"HAS DATA");
gloablOnWherehouse.arTableDataSelected = [content objectForKey:#"DataList_SPI_DetailCollection"];
[self.tableViewWhereHoseList reloadData];
labelStatus.text = #"F11";
}
}
else
{
NSLog(#"response %#",responseData);
}
}
- (void) requestEWIServiceFail:(EWIConnector *)connector error:(NSError *)error{
NSLog(#"request fail %#",connector);
}
- (NSString *)getString:(NSString *)string
{
return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (IBAction)btnf10
{
NSMutableDictionary *content = [NSMutableDictionary dictionary];
[content setValue:[[AppSetting sharedInstance] token] forKey:#"ewitoken"];
//[content setValue:gloablOnWherehouse.selectedWhereHouse forKey:#"model_Name"];
[[EWIConnector connector] requestEWIService:#"special_selected_f10" requestData:content delegate:self];
}
UITableView2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
globlOnDisplayEffect = [GlobalVariable sharedInstance];
globlOnDisplayEffect.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
[self.tableViewDetailList reloadData];
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (globlOnDisplayEffect.arTableDataSelected)?[globlOnDisplayEffect.arTableDataSelected count]: 1;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"DisplayEffectQtyViewCell";
DisplayEffectQtyViewCell *cell = [self.tableViewDetailList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"DisplayEffectQtyViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (globlOnDisplayEffect.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:globlOnDisplayEffect.arTableDataSelected];
if (myMutbleArray) {
NSDictionary *myDic = [globlOnDisplayEffect.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_DetailF10"];
NSString *f10_cmpt = [self getString:[cont objectForKey:#"f10_cmpt"]];
NSString *f10_dt = [self getString:[cont objectForKey:#"f10_dt"]];
NSString *f10_item = [self getString:[cont objectForKey:#"f10_item"]];
NSString *f10_lot = [self getString:[cont objectForKey:#"f10_lot"]];
NSString *f10_model = [self getString:[cont objectForKey:#"f10_model"]];
NSString *f10_of = [self getString:[cont objectForKey:#"f10_of"]];
NSString *f10_semi = [self getString:[cont objectForKey:#"f10_semi"]];
NSString *f10_tm = [self getString:[cont objectForKey:#"f10_tm"]];
NSString *f10_uncmp = [self getString:[cont objectForKey:#"f10_uncmp"]];
[cell setf10_cmpt:f10_cmpt setf10_dt:f10_dt setf10_item:f10_item setf10_lot:f10_lot setf10_model:f10_model setf10_of:f10_of setf10_semi:f10_semi setf10_tm:f10_tm setf10_uncmp:f10_uncmp];
}
}
}
return cell;
}
- (void) requestEWIServiceStart:(EWIConnector *)connector{
NSLog(#"start %#",connector.endpoint);
}
TO Check if view controller already push or not.
if(![self.navigationController.topViewController isKindOfClass:[NewViewController class]]) {
[self.navigationController pushViewController:newViewController animated:YES];
}

Duplicate data when scrolling a UITableView

I had a problem with tableview which is when the table first shows everything looks great but if I scroll up and and down, NSLog(#"page name : %#", cell.pageName.text); output value will be duplicate and it will cause the scrolling to be lagged. This is my code :
#import "HomeTVC.h"
#import "facebook.h"
#import "HomeTVCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#interface HomeTVC ()<UITableViewDataSource, UITableViewDelegate>
{
NSDictionary *userPageLikesParams;
NSArray *pagesInfo;
}
#end
#implementation HomeTVC
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.delegate = self;
self.tableView.dataSource = self;
facebook *fb = [[facebook alloc] init];
userPageLikesParams = #{#"fields": #"about,name,created_time,picture",#"limit": #"10"} ;
[fb getUserPagelikes:userPageLikesParams completionHandler:^(NSDictionary *pagesResult) {
if (pagesResult != nil) {
pagesInfo = pagesResult[#"data"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"table count : %d", (int)pagesInfo.count);
if (pagesInfo == nil) {
return 0;
} else {
return pagesInfo.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CellIdentifier";
HomeTVCell *cell = (HomeTVCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[HomeTVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSURL *imageURL = [NSURL URLWithString:[pagesInfo[indexPath.row] valueForKeyPath:#"picture.data.url"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
// UIImage *pageProfileImage = [UIImage imageWithData:imageData];
// NSLog(#"pages info : %#", pagesInfo[indexPath.row]);
// NSLog(#"pages info image URL : %#", imageURL);
// cache the image using sdwebimage
cell.pageProfilePic.layer.backgroundColor=[[UIColor clearColor] CGColor];
cell.pageProfilePic.layer.borderWidth= 2.0;
cell.pageProfilePic.layer.masksToBounds = YES;
cell.pageProfilePic.layer.borderColor=[[UIColor whiteColor] CGColor];
cell.pageProfilePic.layer.cornerRadius= 30.0;
[cell.pageProfilePic sd_setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
//cell.pageProfilePic.image = pageProfileImage;
cell.pageName.text = pagesInfo[indexPath.row][#"name"];
NSLog(#"page name : %#", cell.pageName.text);
return cell;
}
Thanks in advance.

Register Nib in ViewDidLoad Thread 1 exc bad access table view

I am getting a Thread 1, EXC: BAD ACCESS error on my [self.tableView registerNib:nib forCellReuseIdentifier:#"InboxCell"]; line. Everything was working fine but then I tried to bring in a BackroundView swift file, which was more of a headache then it was worth.
I deleted the BackgroundView swift file and cleaned it but now I have an error I cant figure out. I have a InboxCell.xib custom cell. Please hold my hand through it. Any help would be much appreciated! Here is my code:
//InboxTableViewController.h
#import "InboxCell.h"
#interface InboxTableViewController : UITableViewController
//this is property for the data source
#property (nonatomic, strong) NSArray *messages;
//something for showing image
#property (nonatomic, strong) PFObject *selectedMessage;
//for showing video
#property (nonatomic, strong) MPMoviePlayerController *moviePlayer;
- (IBAction)logout:(id)sender;
//set thumbnail
#property (nonatomic, strong) UIImage *thumbnail;
-(void)setThumbnailFromImage:(UIImage *)image;
#end
//.m
#interface InboxTableViewController ()
#end
#implementation InboxTableViewController
-(void)loadView
{
}
- (void)viewDidLoad {
[super viewDidLoad];
//THIS IS CUSTOM CELL!!!!!!!
UINib *nib = [UINib nibWithNibName:#"InboxCell" bundle:nil];
//register this nib to contain cell
/*THIS IS EXC ERROR*/
[self.tableView registerNib:nib forCellReuseIdentifier:#"InboxCell"];
//video alloc here so its reused for every video in inbox.
self.moviePlayer = [[MPMoviePlayerController alloc] init];
//Determining if a current user is logged in
PFUser *currentUser = [PFUser currentUser];
if (currentUser) {
NSLog(#"%#", currentUser.username);
} else {
[self performSegueWithIdentifier:#"showLogin" sender: self];
}
}
//// In case it hasnt been logged in after a while
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//return nav and controller bar
[self.navigationController.navigationBar setHidden:NO];
[self.tabBarController.tabBar setHidden:NO];
PFQuery *query = [PFQuery queryWithClassName:#"Messages"];
// prevents error when running for first time in a while
if ([[PFUser currentUser] objectId] == nil) {
NSLog(#"No objectID");
} else {
[query whereKey:#"recipientIds" equalTo:[[PFUser currentUser] objectId]];
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"error %# %#", error, [error userInfo]);
} else {
self.messages = objects;
[self.tableView reloadData];
NSLog(#"Got %lu messages", (unsigned long)[self.messages count]);
}
}];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showLogin"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
}
else if ([segue.identifier isEqualToString:#"showImage"]) {
//setting it so image tab wont pop up
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
ImageViewController *imageViewController = (ImageViewController *)segue.destinationViewController;
imageViewController.message = self.selectedMessage;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedMessage = [self.messages objectAtIndex:indexPath.row];
NSString *fileType = [self.selectedMessage objectForKey:#"fileType"];
if ([fileType isEqualToString:#"image"]) { //if image file
[self performSegueWithIdentifier:#"showImage" sender:self];
}
else {
//file type is video
PFFile *videoFile = [self.selectedMessage objectForKey:#"file"]; //getting the file
//now getting the URL property which is a string
NSURL *fileUrl = [NSURL URLWithString:videoFile.url];
//set the url for the movie player
self.moviePlayer.contentURL = fileUrl;
//prepare for file
[self.moviePlayer prepareToPlay];
//this is a quick thumbnail while it loads
// [[self.moviePlayer ]; NOT WORKING HERE
//Add video to view controller so you can see it
[self.view addSubview:self.moviePlayer.view];
//setting it to screen size CAN SET TO ANYSIZE!!!!!!!
[self.moviePlayer setFullscreen:YES animated:YES];
}
/* //this portion is to delete it after its viewed
NSMutableArray *recipientIds = [NSMutableArray arrayWithArray:[self.selectedMessage objectForKey:#"recipientIds"]];
//this is for each one individually
if ([recipientIds count] == 1) {
//last recipient delete
[self.selectedMessage deleteInBackground];
}
else {
//remove the recipients and save it
[recipientIds removeObject:[[PFUser currentUser] objectId]];
//now you have to update recipients array with new data
[self.selectedMessage setObject:recipientIds forKey:#"recipientIds"];
[self.selectedMessage saveInBackground];
} */
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// always use the count of data source
return [self.messages count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
/*CUSTOM CELL CODE */
InboxCell *cell = [tableView dequeueReusableCellWithIdentifier:#"InboxCell" forIndexPath:indexPath];
PFObject *message = [self.messages objectAtIndex:indexPath.row];
cell.titleLabel.text = [message objectForKey:#"senderName"];
//Date
NSDate *updated = [message updatedAt];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"EEE, MMM d, h:mm a"];
cell.createdAtLabel.text = [NSString stringWithFormat:#"Filmed At: %#", [dateFormat stringFromDate:updated]];
// customizing the image next to the message to determine whether its a video or image.
NSString *fileType = [message objectForKey:#"file_type"];
if ([fileType isEqualToString:#"image"]) { // must add icons
cell.thumbnailView.image = [UIImage imageNamed: #"icon_image.png"];
// cell.imageView.image is the way to have a picture in a cell.
}
else {
cell.thumbnailView.image = [UIImage imageNamed:#"icon_video"];
}
return cell;
}
//this is used as a thumbnail before video plays
//- (UIImage *)thumbnailFromVideoAtURL:(NSURL *)url
//{
// AVAsset *asset = [AVAsset assetWithURL:url];
//
// // Get thumbnail at the very start of the video
// CMTime thumbnailTime = [asset duration];
// thumbnailTime.value = 0;
//
// // Get image from the video at the given time
// AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
//
// CGImageRef imageRef = [imageGenerator copyCGImageAtTime:thumbnailTime actualTime:NULL error:NULL];
// UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
// CGImageRelease(imageRef);
//
// return thumbnail;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
return 100;
}
else {
return 100;
}
}
- (IBAction)logout:(id)sender {
[PFUser logOut];
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
- (IBAction)refresh:(id)sender {
[self.tableView reloadData];
[sender endRefreshing];
}
//setting thumbnail for cell
-(void)setThumbnailFromImage:(UIImage *)image
{
CGSize origImageSize = image.size;
CGRect newRect = CGRectMake(0, 0, 104, 76);
float ratio = MAX(newRect.size.width / origImageSize.width, newRect.size.height / origImageSize.height);
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect cornerRadius:5.0];
[path addClip];
CGRect projectRect;
projectRect.size.width = ratio * origImageSize.width;
projectRect.size.height = ratio * origImageSize.height;
projectRect.origin.x = (newRect.size.width - projectRect.size.width) / 2.0;
projectRect.origin.y = (newRect.size.height - projectRect.size.height) / 2.0;
[image drawInRect:projectRect];
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
self.thumbnail = smallImage;
UIGraphicsEndImageContext();
}
#end
Your issue is being caused by the empty loadView method. Never leave that method empty. Either remove the method or give it a proper implementation of creating the view controller's main view and setting self.view.

How to store PFUser objectId with RecipientId

I use Parse.com for backend, I've two views : InboxView (where I receive images from friends), and ChatView.
When I send images, I send images with recipientIds of user (that can be multiple users) in "Messages" class (parse).
I receive images in my InboxView, I can see in cell for row the name of the friend that send images.
I would like that when I select a row (username who sends me image) that stores the PFUser objectId of the user who sends me the image, and not all of the recipientIds.
How can I make that ?
Here is my code :
Inbox.h :
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import <MediaPlayer/MediaPlayer.h>
#interface InboxViewController : UITableViewController
#property (nonatomic, strong) NSArray *messages;
#property (nonatomic, strong) PFObject *selectedMessage;
#property (nonatomic, strong) MPMoviePlayerController *moviePlayer;
#property (nonatomic, strong) UIImage *MindleNav;
- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height;
#end
and inbox.m :
#import "InboxViewController.h"
#import "ImageViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "LoginViewController.h"
#import "FriendsViewController.h"
#interface InboxViewController ()
#end
#implementation InboxViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.MindleNav = [UIImage imageNamed:#"MindleNavItem.png"];
UIImage *newImage = [self resizeImage:self.MindleNav toWidth:150.0f andHeight:48.0f];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:newImage];
self.MindleNav = newImage;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
PFQuery *query = [PFQuery queryWithClassName:#"Messages"];
[query whereKey:#"recipientIds" equalTo:[[PFUser currentUser] objectId]];
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
else {
// We found messages!
self.messages = objects;
[self.tableView reloadData];
}
}];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.messages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
PFObject *message = [self.messages objectAtIndex:indexPath.row];
cell.textLabel.text = [message objectForKey:#"senderName"];
NSString *fileType = [message objectForKey:#"fileType"];
if ([fileType isEqualToString:#"image"]) {
cell.imageView.image = [UIImage imageNamed:#"icon_image"];
}
else {
// cell.imageView.image = [UIImage imageNamed:#"icon_video"];
}
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.selectedMessage = [self.messages objectAtIndex:indexPath.row];
NSString *fileType = [self.selectedMessage objectForKey:#"fileType"];
if ([fileType isEqualToString:#"image"]) {
[self performSegueWithIdentifier:#"showImage" sender:self];
}
else {
// File type is text
// // File type is video
// PFFile *videoFile = [self.selectedMessage objectForKey:#"file"];
// NSURL *fileUrl = [NSURL URLWithString:videoFile.url];
// self.moviePlayer.contentURL = fileUrl;
// [self.moviePlayer prepareToPlay];
// UIImage *thumbnail = [self thumbnailFromVideoAtURL:self.moviePlayer.contentURL];
//
//// [self.moviePlayer thumbnailImageAtTime:0 timeOption:MPMovieTimeOptionNearestKeyFrame];
//
// // Add it to the view controller so we can see it
// UIImageView *imageView = [[UIImageView alloc] initWithImage:thumbnail];
// [self.moviePlayer.backgroundView addSubview:imageView];
// [self.moviePlayer setFullscreen:YES animated:YES];
}
// Delete it!
NSMutableArray *recipientIds = [NSMutableArray arrayWithArray:[self.selectedMessage objectForKey:#"recipientIds"]];
NSLog(#"Recipients: %#", recipientIds);
if ([recipientIds count] == 1) {
// Last recipient - delete!
// [self.selectedMessage deleteInBackground];
}
else {
// Remove the recipient and save
// [recipientIds removeObject:[[PFUser currentUser] objectId]];
// [self.selectedMessage setObject:recipientIds forKey:#"recipientIds"];
// [self.selectedMessage saveInBackground];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showImage"]) {
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
ImageViewController *imageViewController =
(ImageViewController *)segue.destinationViewController;
imageViewController.message = self.selectedMessage;
}
}
- (UIImage *)thumbnailFromVideoAtURL:(NSURL *)url
{
AVAsset *asset = [AVAsset assetWithURL:url];
// Get thumbnail at the very start of the video
CMTime thumbnailTime = [asset duration];
thumbnailTime.value = 0;
// Get image from the video at the given time
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:thumbnailTime actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return thumbnail;
}
- (UIImage *)resizeImage:(UIImage *)truckImage toWidth:(float)width andHeight:(float)height {
CGSize newSize = CGSizeMake(width, height);
CGRect newRectangle = CGRectMake(0, 0, width, height);
UIGraphicsBeginImageContext(newSize);
[self.MindleNav drawInRect:newRectangle];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
#end

Resources