How to parse a json file with /n and br line breaks in iPhone? - objective-c

I am currently parsing a json file from a web server which was generated using a php son generator.But now the json file has /n and br tags in the content and when i parse the file,the app displays the /n and br tags.
Heres my code:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
static NSString *cellIdentifier=#"identity";
CustomCell2 *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.loader.hidden = NO;
[loader startAnimating];
[[NSBundle mainBundle]loadNibNamed:#"CustomCell11" owner:self options:nil];
cell=(CustomCell2 *)tblCell;
NSMutableArray *dictionaryObject=[_newsArray objectAtIndex:indexPath.row];
lblMain.text=[dictionaryObject valueForKey:#"MainHeadline"];
lblSummary.text=[dictionaryObject valueForKey:#"Story"];
lblEdition.text=[dictionaryObject valueForKey:#"Edition"];
//lblStory.text=[dictionaryObject valueForKey:#"FullStory"];
lblDate.text=[dictionaryObject valueForKey:#"PublishDate"];
lblAuthor.text=[dictionaryObject valueForKey:#"Author"];
dispatch_queue_t queue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSURL* url = [NSURL URLWithString:[dictionaryObject valueForKey:#"ImagePath"]];
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImageView *imgViewThumb=[[UIImageView alloc]initWithFrame:imgView.frame];
[imgViewThumb setImage:[UIImage imageWithData:data]];
dispatch_async(dispatch_get_main_queue(), ^{
//cell image added below dispath..patching,il change this later..brrrrrr!!
[cell addSubview:imgViewThumb];
//cell.ImagePath.UIImage = imgViewThumb;
});
// [cell addSubview:imgViewThumb];
});
});
//what the heck???
return cell;
}
#pragma mark -methods
-(void)retrieveData{
NSURL * url =[NSURL URLWithString:getDataURL];
NSData *data =[NSData dataWithContentsOfURL:url];
_json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
_newsArray = [[NSMutableArray alloc]init];
for (int i = 0; i < _json.count; i++){
{
NSString * cID =[[_json objectAtIndex:i]objectForKey:#"ID"];
NSString * cName = [[_json objectAtIndex:i]objectForKey:#"MainHeadline"];
NSString * cState =[[_json objectAtIndex:i]objectForKey:#"FullStory"];
NSString * cPopulation =[[_json objectAtIndex:i]objectForKey:#"Edition"];
NSString * cCountry =[[_json objectAtIndex:i]objectForKey:#"PublishDate"];
NSString * cStory =[[_json objectAtIndex:i]objectForKey:#"Story"];
NSString * cAuthor =[[_json objectAtIndex:i]objectForKey:#"Author"];
UIImage *cImage =[[_json objectAtIndex:i]objectForKey:#"ImagePath"];
UIImage *cLogo =[[_json objectAtIndex:i]objectForKey:#"Logo"];
CustomCell2 *myCity = [[CustomCell2 alloc]initWithCityID:cID andCityName:cName andCityState:cState andCityPopulation:cPopulation andCityCountry:cCountry andStory:cStory andImagePath:cImage andAuthor:cAuthor andLogo:cLogo];
[_newsArray addObject:myCity];``
}
//[self.tblView reloadData];
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"detailView" sender:self];
}
#pragma mark - SlideNavigationController Methods -
- (BOOL)slideNavigationControllerShouldDisplayLeftMenu
{
return YES;
}

An example of better simpler code (in an answer for formatting):
// Current
for (int i = 0; i < _json.count; i++){
{
NSString * cID =[[_json objectAtIndex:i]objectForKey:#"ID"];
NSString * cName = [[_json objectAtIndex:i]objectForKey:#"MainHeadline"];
NSString * cState =[[_json objectAtIndex:i]objectForKey:#"FullStory"];
...
// Simplified
for (NSDictionary *item in _json) {
NSString * cID = item[#"ID"];
NSString * cName = item[#"MainHeadline"];
NSString * cState =item[#"FullStory"];
...
Studying the language documentation can payoff in simpler and clear code.
Also elimination of duplication can reduce simple errors.

Related

How to reload data into NSTableView?

I am fairly new to Objective-C and I find there are a lot of tutorials for iOS and UITableView but almost none for OS X Apps via NSTableView. I have built a method to retrieve my data but I get an error on the last line:
"Property tableView not found on object type ProductsViewController".
I do not know the correct way to reload my data into my table or if I even need to use an NSTableView for this specific instance? Is there a better way to display my data than using NSTableView?
#import "ProductsViewController.h"
#import "Product.h"
#define getDataURL #"http://myurl"
#interface ProductsViewController ()
#end
#implementation ProductsViewController
#synthesize jsonArray, productsArray;
- (void)viewDidLoad {
[super viewDidLoad];
[self retrieveData];
}
-(NSInteger)numberOfRowsInTable:(NSTableView *)tableView{
return productsArray.count;
}
- (void) retrieveData{
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
productsArray = [[NSMutableArray alloc] init];
for(int i = 0; i < jsonArray.count; i++){
NSString * pID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString * pName = [[jsonArray objectAtIndex:i] objectForKey:#"product_name"];
NSString * pPrice = [[jsonArray objectAtIndex:i] objectForKey:#"product_price"];
NSString * pDescription = [[jsonArray objectAtIndex:i] objectForKey:#"product_description"];
NSString * pImage = [[jsonArray objectAtIndex:i] objectForKey:#"product_image"];
NSString * pDownload = [[jsonArray objectAtIndex:i] objectForKey:#"product_download"];
NSString * pVideo = [[jsonArray objectAtIndex:i] objectForKey:#"product_video"];
NSString * pFeatured = [[jsonArray objectAtIndex:i] objectForKey:#"featured"];
[productsArray addObject:[[Product alloc] initWithProduct_Name: pName andProduct_Price:pPrice andProduct_Description:pDescription andProduct_Image:pImage andProduct_Download:pDownload andProduct_Video:pVideo andProduct_Featured:pFeatured andProduct_ID:pID]];
}
[self.tableView reloadData];
}
You need to implement the required delegate methods for the NSTableViewDataSource protocol. Specifically, you need these two:
numberOfRowsInTableView:
tableView:objectValueForTableColumn:row:
The table view will then call these methods for the data it wants.
In addition, there's a great tutorial over at raywenderlich.com about using NSTableViews.

Loading image from url ios 8 objective c

i´m trying to obtain the imagen from this url[#"file:///var/mobile/Media/DCIM/100APPLE/IMG_0158.JPG"], but i can´t.
Always is nil.
this is my code:
NSData *data = [NSData dataWithContentsOfURL: #"file:///var/mobile/Media/DCIM/100APPLE/IMG_0158.JPG"];
UIImage *image = [UIImage imageWithData:data];
self.pruebaTmp.image = image;
i obtain the url with this code:
if (asset) {
// get photo info from this asset
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = YES;
[[PHImageManager defaultManager]
requestImageDataForAsset:asset
options:imageRequestOptions
resultHandler:^(NSData *imageData, NSString *dataUTI,
UIImageOrientation orientation,
NSDictionary *info)
{
NSURL *path = [info objectForKey:#"PHImageFileURLKey"];
//asignamos el path de la imágen seleccionada en galeria
self.pathImagen = path;
}];
}
if someone could help i would be very grateful, because i can´t load the image with the url obtained.
you can`t not get UIimage or metadata from that url.
you can get UIImage from local Identifier of access
PHFetchResult *savedAssets = [PHAsset fetchAssetsWithLocalIdentifiers:#[localIdentifier] options:nil];
[savedAssets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//this gets called for every asset from its localIdentifier you saved
//PHImageRequestOptionsDeliveryModeHighQualityFormat
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = NO;
imageRequestOptions.deliveryMode = PHImageRequestOptionsResizeModeFast;
imageRequestOptions.resizeMode = PHImageRequestOptionsResizeModeFast;
[[PHImageManager defaultManager]requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFill options:imageRequestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
NSLog(#"get image from result");
if (result) {
}
}];
imageRequestOptions = nil;
}];

objectatindex outside of loop?

This is a question hard to ask but I'm going to give it a shot anyways. I'm trying to retrieving the contents of an NSDictionary outside of the UITableCell loop. Right now, when I do retrieve its content via:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
everything works fine. But outside of that loop, in a void function of its own, the number retrieved is 0.
- (void)getVideoList{
NSString *ensdsds = #"z9yDgV3ONSU";
for (int i=0; i< [self.youtubePaginator.results count]; i++){
NSDictionary *photoshoots = [self.youtubePaginator.results objectAtIndex:i];
NSString * videoId = photoshoots[#"videoID"];
NSLog(#"Newly %#: ", videoId);
NSString *urlStrings = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/videos?part=id%%2C+snippet%%2C+contentDetails%%2C+statistics&id=%#&key=78587868", videoId];
NSLog(#"Arries %#", urlStrings);
NSURL *urlstats = [NSURL URLWithString:urlStrings];
NSURLRequest *requeststats = [NSURLRequest requestWithURL:urlstats];
AFHTTPRequestOperation *operationtwo = [[AFHTTPRequestOperation alloc] initWithRequest:requeststats];
operationtwo.responseSerializer = [AFJSONResponseSerializer serializer];
[operationtwo setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operationtwo, id responseObjected)
{
NSDictionary *itemed = [responseObjected objectForKey:#"items"];
for (NSDictionary *itemest in itemed )
{
YouTubeVideo *youTubeVideo = [[YouTubeVideo alloc] init];
NSDictionary* stats = [itemest objectForKey:#"statistics"];
youTubeVideo.likesCount = [stats objectForKey:#"likeCount"];
youTubeVideo.viewsCount = [stats objectForKey:#"viewCount"];
NSDictionary* channelInfo = [itemest objectForKey:#"snippet"];
youTubeVideo.channelInfo = [channelInfo objectForKey:#"channelId"];
youTubeVideo.videoUploader = [channelInfo objectForKey:#"channelTitle"];
NSLog(#"True To: %#", youTubeVideo.videoUploader);
[self.thunder addObject:youTubeVideo];
}} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error loading %#", error);
}];
[operationtwo start]; }
}
The above code returns nothing. How do I incorporate NSIndexPath in the void function and still be able to call [self getVideoList]; in viewDidLoad.
Hope that makes sense? :/
You can get the imageURL in getVideoList by passing NSIndexPath as a parameter , you just need to create a global NSString object if you want to access it globally or you can return extracted imageURL as a return value.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * imageURL = [self getVideoList:indexPath];
// Write your code to perform operation with the image URL.
}
Here is the getVideoList method
- (NSString *)getVideoList:(NSIndexPath *)indexPath{
NSDictionary *photoshoots = [self.youtubePaginator.results objectAtIndex:indexPath.Row];
NSString * imageURL = photoshoots[#"avatar_url"];
NSLog(#"Newly %#: ", imageURL);
NSLog(#"To find us: [%d]:%#",i,self.youtubePaginator.results[i]);
return imageURL;
}
You can update the code as per your requirement.

iOS 7 NSURLSession Download multiple files in Background

I want to download a List of files using NSUrlSession.
I have a variable for counting the successful downloads #property (nonatomic) int downloadsSuccessfulCounter;. While the files are being downloaded I disable the Download Button. When the counter is equal to the download list size, I enable the button again and set the counter to 0. I do this in the method:
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
...
[[NSOperationQueue mainQueue] addOperationWithBlock:^ {
downloadsSuccessfulCounter++;
if(downloadsSuccessfulCounter == self.downloadList.count) {
NSLog(#"All downloads finished");
[self.syncButton setEnabled:YES];
downloadsSuccessfulCounter = 0;
}
}];
}
Everything is working fine, but when I open again the ViewController I get the message A background URLSession with identifier com.myApp already exists!. The counter is not set to 0 and the UI elements (UIButtons, UILabels) are not responding.
I guess the problem is because the NSURLSession is still open but I'm not really sure about how it works.
I have tried all the tutorials, but 99% of them are only for downloading 1 file, not more than 1...
Any ideas?
Here is my code:
...
#property (nonatomic, strong) NSURLSession *session;
...
- (void)viewDidLoad {
[super viewDidLoad];
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.downloadList = [[NSMutableArray alloc] init];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:#"com.myApp"];
sessionConfiguration.HTTPMaximumConnectionsPerHost = 5;
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
}
When I press the Download ButtonI call this method (
I have a Downloadable object which contains a NSURLSessionDownloadTask):
-(void)startDownload {
for (int i=0; i<[self.downloadList count]; i++) {
Downloadable *d = [self.downloadList objectAtIndex:i];
if (!d.isDownloading) {
if (d.taskIdentifier == -1) {
d.downloadTask = [self.session downloadTaskWithURL:[NSURL URLWithString:d.downloadSource]];
}else {
d.downloadTask = [self.session downloadTaskWithResumeData:fdi.taskResumeData];
}
d.taskIdentifier = d.downloadTask.taskIdentifier;
[d.downloadTask resume];
d.isDownloading = YES;
}
}
}
When the app is in Background:
-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
if ([downloadTasks count] == 0) {
if (appDelegate.backgroundTransferCompletionHandler != nil) {
void(^completionHandler)() = appDelegate.backgroundTransferCompletionHandler;
appDelegate.backgroundTransferCompletionHandler = nil;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
completionHandler();
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = #"All files downloaded";
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}];
}
}
}];
}
So, as I mentioned in my comments, the issue is that each File requires a unique NSURLSession, and each NSURLSession requires a NSURLSessionConfiguration with a unique identifier.
I think that you were close - and probably more proper than me in certain aspects...
You just need to create a structure to pass unique IDs into unique Configurations, to populate unique Sessions (say that 10x fast).
Here's what I did:
/*
* Retrieves the List of Files to Download
* Also uses the size of that list to instantiate items
* In my case, I load a character returned text file with the names of the files that I want to download
*/
- (void) getMediaList {
NSString *list = #"http://myserver/media_list.txt";
NSURLSession *session = [NSURLSession sharedSession]; // <-- BASIC session
[[session dataTaskWithURL:[NSURL URLWithString:list]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *stringFromData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
// Populate Arrays
REMOTE_MEDIA_FILE_PATHS = [stringFromData componentsSeparatedByString:#"\n"];
[self instantiateURLSessions:[REMOTE_MEDIA_FILE_PATHS count]];
// Start First File
[self getFile:[REMOTE_MEDIA_FILE_PATHS objectAtIndex:downloadCounter]:downloadCounter]; // this variable is 0 at the start
}]
resume];
}
/*
* This sets Arrays of Configurations and Sessions to the proper size
* It also gives a unique ID to each one
*/
- (void) instantiateURLSessions : (int) size {
NSMutableArray *configurations = [NSMutableArray array];
NSMutableArray *sessions = [NSMutableArray array];
for (int i = 0; i < size; i++) {
NSString *index = [NSString stringWithFormat:#"%i", i];
NSString *UniqueIdentifier = #"MyAppBackgroundSessionIdentifier_";
UniqueIdentifier = [UniqueIdentifier stringByAppendingString:index];
[configurations addObject: [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:UniqueIdentifier]];
[sessions addObject:[NSURLSession sessionWithConfiguration: [configurations objectAtIndex:i] delegate: self delegateQueue: [NSOperationQueue mainQueue]]];
}
NSURL_BACKGROUND_CONFIGURATIONS = [NSArray arrayWithArray:configurations];
NSURL_BACKGROUND_SESSIONS = [NSArray arrayWithArray:sessions];
}
/*
* This sets up the Download task for each file, based off of the index of the array
* It also concatenates the path to the actual file
*/
- (void) getFile : (NSString*) file :(int) index {
NSString *fullPathToFile = REMOTE_MEDIA_PATH; // Path To Server With Files
fullPathToFile = [fullPathToFile stringByAppendingString:file];
NSURL *url = [NSURL URLWithString:fullPathToFile];
NSURLSessionDownloadTask *downloadTask = [[NSURL_BACKGROUND_SESSIONS objectAtIndex:index ] downloadTaskWithURL: url];
[downloadTask resume];
}
/*
* Finally, in my delegate method, upon the completion of the download (after the file is moved from the temp data), I check if I am done and if not call the getFiles method again with the updated counter for the index
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// Get the documents directory URL
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:LOCAL_MEDIA_PATH];
NSURL *customDirectory = [NSURL fileURLWithPath:dataPath];
// Get the file name and create a destination URL
NSString *sendingFileName = [downloadTask.originalRequest.URL lastPathComponent];
NSURL *destinationUrl = [customDirectory URLByAppendingPathComponent:sendingFileName];
// Move the file
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager moveItemAtURL:location toURL:destinationUrl error: &error]) {
// List
[self listCustomDirectory];
if(downloadCounter < [REMOTE_MEDIA_FILE_PATHS count] -1) {
// Increment Counter
downloadCounter++;
// Start Next File
[self getFile:[REMOTE_MEDIA_FILE_PATHS objectAtIndex:downloadCounter]:downloadCounter];
}
else {
// FINISH YOUR OPERATION / NOTIFY USER / ETC
}
}
else {
NSLog(#"Damn. Error %#", error);
// Do Something Intelligent Here
}
}

-[__NSCFConstantString allKeys]: unrecognized selector sent to instance 0xf9ac8

My app when I run it on my phone I get this error:
I just tried to parse a json and trying to use images in two column of custom cell, but my images on scroll are mis-placed.
int index=indexPath.row*2;
int newindex=index+1;
NSDictionary *u = [[results objectAtIndex:index]mutableCopy ];
NSLog(#"NSDictionary *u = [results objectAtIndex:index] %#",u);
NSDictionary *u1 = [[results objectAtIndex:newindex]mutableCopy];
NSLog(#"NSDictionary *u1 = [results objectAtIndex:newindex] %#",u1);
But if i use both index and newindex same value it works.
:-
:-
Code :
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil suffix:(NSString *)_suffix{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.suffix = _suffix;
}
return self;
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)_tableView{
return 1;
}
//my new
- (NSInteger)tableView:(UITableView *)_tableView numberOfRowsInSection:(NSInteger)section{
int resultCount = [results count];
labelResultsCount.text = [NSString stringWithFormat:#"%d",resultCount];
return resultCount/2;
}
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// NSString* CellIdentifier = [NSString stringWithFormat:#"ident_%d",indexPath.row];
static NSString *CellIdentifier = #"ResultCell";
ResultCell *cell = (ResultCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
NSArray *a = [[NSBundle mainBundle] loadNibNamed:#"ResultCell" owner:self options:nil];
cell = (ResultCell *)[a objectAtIndex:0];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
int index=[(indexPath.row*2) copy];
int newindex=[(index+1) copy];
// save badge in dictionaory and get here and show in lable
NSDictionary *u = [[results objectAtIndex:index]mutableCopy ];
NSLog(#"NSDictionary *u = [results objectAtIndex:newindex] %#",u);
NSDictionary *u1 = [[results objectAtIndex:newindex]mutableCopy];
NSLog(#"NSDictionary *u1 = [results objectAtIndex:indexPath.row*2+1 newindex] %#",u1);
#try {
/* fullName */
NSString *nickName = [u objectForKey:#"nickName"];
cell.labelName.text = nickName;
NSString *nickName1 = [u1 objectForKey:#"nickName"];
cell.labelName1.text = nickName1;
/* chat notification*/
cell.imageViewNotification.hidden=0;
cell.imageViewNotification1.hidden=0;
NSString *badge = [u objectForKey:#"badge"];
NSString *badge1 = [u1 objectForKey:#"badge"];
if([badge intValue]>0)
{
cell.imageViewNotification.hidden=0;
cell.labelNotification.text = badge;
NSLog(#"inside > 0 %#",badge);
}
else if([badge intValue]<=0)
{
cell.imageViewNotification.hidden=1;
cell.labelNotification.text=#"";
NSLog(#"%#",badge);
}
if([badge1 intValue]>0)
{
cell.imageViewNotification1.hidden=0;
cell.labelNotification1.text = badge1;
NSLog(#"inside > 0 %#",badge1);
}
else if([badge1 intValue]<=0)
{
cell.imageViewNotification1.hidden=1;
cell.labelNotification1.text=#"";
NSLog(#"%#",badge1);
}
/*..................*/
/* distance */
id distance = [u objectForKey:#"distance"];
if([distance isKindOfClass:[NSString class]]){
cell.labelDistance.text = distance;
cell.imageViewDistance.hidden = 0;
}else{
cell.imageViewDistance.hidden = 1;
cell.labelDistance.text = #"";
}
id distance1 = [u1 objectForKey:#"distance"];
if([distance1 isKindOfClass:[NSString class]]){
cell.labelDistance1.text = distance1;
cell.imageViewDistance1.hidden = 0;
}else{
cell.imageViewDistance1.hidden = 1;
cell.labelDistance1.text = #"";
}
/* online */
NSNumber *online = [u objectForKey:#"online"];
cell.imageViewOnline.image = [online intValue] ? [UIImage imageNamed:#"circle_online.png"] : [UIImage imageNamed:#"circle_offline_red.png"];
NSNumber *online1 = [u1 objectForKey:#"online"];
cell.imageViewOnline1.image = [online1 intValue] ? [UIImage imageNamed:#"circle_online.png"] : [UIImage imageNamed:#"circle_offline_red.png"];
/* buttonProfile */
id d = [u objectForKey:#"thumbnails"];
id d1 = [u1 objectForKey:#"thumbnails"];
if([d isKindOfClass:[NSDictionary class]] ||[d1 isKindOfClass:[NSDictionary class]]){
if([[d allKeys] count]>0 ||[[d1 allKeys] count]>0){
NSString *imageSuffix = [d objectForKey:#"icon"];
NSString *imageSuffix1 = [d1 objectForKey:#"icon"];
NSLog(#"[d allKeys] count]%#", d);
NSLog(#"[d1 allKeys] count]%#", d1);
UIImage *image = [[SharingCenter sharedManager] imageFromCache:imageSuffix];
UIImage *image1 = [[SharingCenter sharedManager] imageFromCache:imageSuffix1];
if(image||image1)
{
[cell.buttonUserProfile setBackgroundImage:image forState:UIControlStateNormal];
[cell.buttonUserProfile1 setBackgroundImage:image1 forState:UIControlStateNormal];
}
else{
NSString *gender = [u objectForKey:#"gender"];
NSString *gender1 = [u1 objectForKey:#"gender"];
UIImage *profileDefualtImage = [gender isEqualToString:#"M"] ? [UIImage imageNamed:#"no_photo_male.png"] : [UIImage imageNamed:#"no_photo_female.png"];
UIImage *profileDefualtImage1 = [gender1 isEqualToString:#"M"] ? [UIImage imageNamed:#"no_photo_male.png"] : [UIImage imageNamed:#"no_photo_female.png"];
[cell.buttonUserProfile setBackgroundImage:profileDefualtImage forState:UIControlStateNormal];
[cell.buttonUserProfile1 setBackgroundImage:profileDefualtImage1 forState:UIControlStateNormal];
/* downlowd Image */
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",WebServicePrefix,imageSuffix]];
__block
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.delegate = self;
[request setPostValue:[NSString stringWithFormat:#"%f",[[SharingCenter sharedManager] currentCoordinate].latitude] forKey:#"lat"];
[request setPostValue:[NSString stringWithFormat:#"%f",[[SharingCenter sharedManager] currentCoordinate].longitude] forKey:#"lon"];
// [[[SharingCenter sharedManager] imagesCache] removeAllObjects];
[request setCompletionBlock:^{
NSData *imageData = [request responseData];
if(imageData){
UIImage *image = [UIImage imageWithData:imageData];
if(image){
[[[SharingCenter sharedManager] imagesCache] setObject:image forKey:imageSuffix];
if([[self.tableView indexPathsForVisibleRows] containsObject:indexPath]){
ResultCell *cell = (ResultCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.buttonUserProfile setBackgroundImage:image forState:UIControlStateNormal];
}
}
}
}];
[request setFailedBlock:^{
NSError *error = request.error;
NSLog(#"%#",error);
}];
/* downlowd Image */
NSURL *url1 = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",WebServicePrefix,imageSuffix1]];
__block
ASIFormDataRequest *request1 = [ASIFormDataRequest requestWithURL:url1];
request1.delegate = self;
[request1 setPostValue:[NSString stringWithFormat:#"%f",[[SharingCenter sharedManager] currentCoordinate].latitude] forKey:#"lat"];
[request1 setPostValue:[NSString stringWithFormat:#"%f",[[SharingCenter sharedManager] currentCoordinate].longitude] forKey:#"lon"];
// [[[SharingCenter sharedManager] imagesCache] removeAllObjects];
[request1 setCompletionBlock:^{
NSData *imageData1 = [request1 responseData];
if(imageData1){
UIImage *image1 = [UIImage imageWithData:imageData1];
if(image1){
[[[SharingCenter sharedManager] imagesCache] setObject:image1 forKey:imageSuffix1];
if([[self.tableView indexPathsForVisibleRows] containsObject:indexPath]){
ResultCell *cell = (ResultCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.buttonUserProfile1 setBackgroundImage:image1 forState:UIControlStateNormal];
}
}
}
}];
[request1 setFailedBlock:^{
NSError *error = request1.error;
NSLog(#"%#",error);
}];
[[self networkQueue] addOperation:request];
[[self networkQueue] addOperation:request1];
}
}
}
else{
NSString *gender = [u objectForKey:#"gender"];
NSString *gender1 = [u1 objectForKey:#"gender"];
UIImage *profileDefualtImage = [gender isEqualToString:#"M"] ? [UIImage imageNamed:#"no_photo_male.png"] : [UIImage imageNamed:#"no_photo_female.png"];
[cell.buttonUserProfile setBackgroundImage:profileDefualtImage forState:UIControlStateNormal];
UIImage *profileDefualtImage1 = [gender1 isEqualToString:#"M"] ? [UIImage imageNamed:#"no_photo_male.png"] : [UIImage imageNamed:#"no_photo_female.png"];
[cell.buttonUserProfile1 setBackgroundImage:profileDefualtImage1 forState:UIControlStateNormal];
}
/* pickStatus */
NSNumber *pickStatus = [u objectForKey:#"pick_status"];
NSNumber *pickStatus1 = [u1 objectForKey:#"pick_status"];
switch ([pickStatus intValue]) {
case 0:
cell.imageViewBorder.image = [UIImage imageNamed:#"border_yellow_transperent.png"];
cell.buttonUserPick.enabled = 1;
[cell.buttonUserPick setBackgroundImage:[UIImage imageNamed:#"button_circle_pick.png"] forState:UIControlStateNormal];
break;
case 1:
cell.imageViewBorder.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick.enabled = 0;
[cell.buttonUserPick setBackgroundImage:[UIImage imageNamed:#"button_circle_wait.png"] forState:UIControlStateDisabled];
break;
case 2:
cell.imageViewBorder.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick.enabled = 1;
[cell.buttonUserPick setBackgroundImage:[UIImage imageNamed:#"button_circle_pick.png"] forState:UIControlStateNormal];
break;
case 3:
cell.imageViewBorder.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick.enabled = 0;
[cell.buttonUserPick setBackgroundImage:[UIImage imageNamed:#"button_circle_date.png"] forState:UIControlStateDisabled];
break;
default:
break;
}
switch ([pickStatus1 intValue]) {
case 0:
cell.imageViewBorder1.image = [UIImage imageNamed:#"border_yellow_transperent.png"];
cell.buttonUserPick1.enabled = 1;
[cell.buttonUserPick1 setBackgroundImage:[UIImage imageNamed:#"button_circle_pick.png"] forState:UIControlStateNormal];
break;
case 1:
cell.imageViewBorder1.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick1.enabled = 0;
[cell.buttonUserPick1 setBackgroundImage:[UIImage imageNamed:#"button_circle_wait.png"] forState:UIControlStateDisabled];
break;
case 2:
cell.imageViewBorder1.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick1.enabled = 1;
[cell.buttonUserPick1 setBackgroundImage:[UIImage imageNamed:#"button_circle_pick.png"] forState:UIControlStateNormal];
break;
case 3:
cell.imageViewBorder1.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick1.enabled = 0;
[cell.buttonUserPick1 setBackgroundImage:[UIImage imageNamed:#"button_circle_date.png"] forState:UIControlStateDisabled];
break;
default:
break;
}
}
#catch (NSException * e) {
NSLog(#"%#",e);
}
#finally {
return cell;
}
}
Educated guess:
This line causes your problem:
if([d isKindOfClass:[NSDictionary class]] ||[d1 isKindOfClass:[NSDictionary class]]){
if([[d allKeys] count]>0 ||[[d1 allKeys] count]>0){
There are 4 different possibilities how the first if will come out:
d and d1 are both NSStrings. Line 2 will not be called
d is NSDictionary, d1 is a NSString. Line 2 will be called
d is NSString, d1 is a NSDictionary. Line 2 will be called
d and d1 are both NSDictionaries. Line 2 will be called.
First case is no problem at all. Last case neither. In case 2 and 3 allKeys will be called on a object that is not a NSDictionary.
You should probably replace it with an "if" that needs both tests to be true.
if([d isKindOfClass:[NSDictionary class]] && [d1 isKindOfClass:[NSDictionary class]]){
^^
Another option would be to check individually.
if([d isKindOfClass:[NSDictionary class]]) {
x = [d allKeys];
}
if([d1 isKindOfClass:[NSDictionary class]]) {
x = [d1 allKeys];
}
You are probably doing something to those NSDictionary objects somewhere, reading their allKeys. But my guess is that the objects you try to fetch from that results array aren't NSDictionary objects but NSString objects.
Try logging their class property to see what you are dealing with (you can also find this out by just looking at the JSON of course).
NSDictionary *u = [[results objectAtIndex:index]mutableCopy ];
NSLog(#"u Class: %#", [u class]);
Also, why are you making a mutableCopy of the object right to a non-mutable NSDictionary object.
Using the following should do the trick normally:
NSDictionary* u = [results objectAtIndex:index];
NSLog(#"u Class: %#", [u class]);
That's a lot of code to look through, but I think this could be the problem:
if([d isKindOfClass:[NSDictionary class]] ||[d1 isKindOfClass:[NSDictionary class]]){
if([[d allKeys] count]>0 ||[[d1 allKeys] count]>0){
This if statement will pass if either d or d1 is a dictionary. If one isn't, it would cause that error you see on the second line. Log the class of d and d1 to see if they're both dictionaries.