How to load image to collectionview from url obtained from json - iphone

I have an IOS app that is using RestKit to pull json formatted data from a server into a CoreData Entity. One of the attributes in the data is a URL for the image associated with the particular article. I'm trying to load that image to my collectionViewController. This is what I've been trying with no success.
From within
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
I am trying this
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSURL *photoURL = [object valueForKey:#"imageUrl"];
NSData *photoData = [NSData dataWithContentsOfURL:photoURL];
cell.cellimg = [[UIImage alloc] initWithData:photoData];
[cell.title setText:[object valueForKey:#"title"]];
If I comment out the attempt to grab and load the image the view loads great with a default image and the titles of the articles received from the json data. Based on that I know everything is coming in correctly.
I have also determined that *photoData is being assigned the correct URL. But each time I encounter the NSData line the console prints out "-[__NSCFString isFileURL]: unrecognized selector sent to instance...."
I honestly don't know if this is even the correct way to do this or if it will even work. I am pretty new at this so any help would be great. Given that I am new some small code examples would really help as well as explaining the proper way to approach this.
Just in case here is the header file where I define *cellimg and *title
#import <UIKit/UIKit.h>
#interface GlobismNewsCollectionViewCell : UICollectionViewCell
#property (strong, nonatomic) IBOutlet UIImage *cellimg;
#property (weak, nonatomic) IBOutlet UILabel *title;
#property (weak, nonatomic) NSURL *imageUrl;
#end

I think you are using NSString as NSURL. So try to use this one...
NSURL *photoURL = [NSURL URLWithString:(NSString *) [object valueForKey:#"imageUrl"]];

Thanks to Dharmbir I had this issue wrapped up within 25 minutes of asking the question!
To clarify for any new guys like me I changed the line Dharmbir suggested so the block looks like this now
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSURL *photoURL = [NSURL URLWithString:(NSString *) [object valueForKey:#"imageUrl"]];
NSData *photoData = [NSData dataWithContentsOfURL:photoURL];
[cell.cellimg setImage:[[UIImage alloc] initWithData:photoData]];
[cell.title setText:[object valueForKey:#"title"]];
Notice the 4th line in the block also changed from this
cell.cellimg = [[UIImage alloc] initWithData:photoData];
to this
[cell.cellimg setImage:[[UIImage alloc] initWithData:photoData]];
I also had to change my *cellimg property to this
#property (strong, nonatomic) IBOutlet UIImageView *cellimg;
from this
#property (strong, nonatomic) IBOutlet UIImage *cellimg;
I had to change to the UIImageView class because the cell in my storyboard is based on the UIImageView Class. Hope this helps a guy in need thanks again Dharmbir!

Related

NSURL Request not working

I am building an app that would run a website through my app. Basically the webView. I had no problems so far since the last xCode update. It basically runs with no errors but it does not work on iOs 6 simulator or device.
.h fle:
#interface ViewController : UIViewController{
IBOutlet UIWebView *nView;
}
.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL * myURL = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
[nView loadRequest:myRequest];
}
If anyone can help I would be grateful. Thank you
I managed to get it working!
.h file:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIWebView *myWebView;
#end
.m file:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url =[NSURL URLWithString:#"http://www.google.com"];
NSURL*request = [NSURLRequest requestWithURL:url];
[[self myWebView]loadRequest:request];
}
I included a property on h file and with some research I got the .m file working too. Although I got an issue saying:
Incompatible pointer types sending 'NSURL *__strong' to parameter of
type 'NSURLRequest *'
Can anybody help to get rid of this issue as well please?

Pass UIImage from one class to another

I'm using this tutorial for capturing images with AVFoundation. I'm trying to get the captured image from CaptureSessionManager (an NSObject class) back to the AROverlayViewController. How do I go about doing this?
I tried putting #property (nonatomic, retain) UIImage *finalImage; in AROverlayViewController.h, then setting arController.finalImage = image; in CaptureSessionManager.m, but the log is saying that finalImage is null.
Any thoughts on how best to do this? Thanks!
There is a property on the class CaptureManager
#property (nonatomic, retain) UIImage *stillImage;
which you can get by this code
UIImage *final = [captureManager stillImage];
I finally got it - add UIImage *test = [captureManager stillImage]; in AROverlayViewController.m. God, that took me forever.
NSData *imageData;
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
[self performSelectorInBackground:#selector(showLoading) withObject:nil];
UIImage *capturedImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
imageData = [[NSData alloc]init];
imageData = UIImagePNGRepresentation(capturedImage);
[imageData retain];
[reader dismissModalViewControllerAnimated: YES];
}
You can pass this NSData to other view you can acces this image.

getting EXC_BAD_ACCESS in Accessing Object in SubView

Maybe a very basic problem, but i don't get it ...
I've written my own class for having Data as an Object in my iPhone app. The class is of Type NSObject. The Class has several NSString propertys and also three objects of other classes.
#interface vcardItem : NSObject {
vCardNitem *PersonName;
NSString *Phone;
NSString *PhotoURL;
vCardTELitem *PhoneData;
NSString *URL;
NSString *eMail;
vCardADRItem *Address;
NSString *Company;
NSString *Role;
int initialised;
}
#property (nonatomic, retain) vCardNitem *PersonName;
#property (nonatomic, retain) NSString *Phone;
#property (nonatomic, retain) NSString *PhotoURL;
#property (nonatomic, retain) vCardTELitem *PhoneData;
#property (nonatomic, retain) NSString *URL;
#property (nonatomic, retain) NSString *eMail;
#property (nonatomic, retain) vCardADRItem *Address;
#property (nonatomic, retain) NSString *Company;
#property (nonatomic, retain) NSString *Role;
#property int initialised;
-(id)initEmpty;
-(id)initWithPayload:(NSString *)payload;
-(void)sendToAddressBook;
-(void)debugVCard;
-(NSString *)getFirstName;
#end
I'm creating an object of vcardItem in a function call within my viewcontroller. The Data is filled and accessible. The function initWithPayload is called and all propertys are set.
Then i open another view for showing Details and call the function setVCard with my vcardItem Object (which is still completeley accessible):
VCardViewController *aVCardViewController = [[VCardViewController alloc] init];
[self presentModalViewController:aVCardViewController animated:YES];
[aVCardViewController setVCard:aVCard];
within the VCardViewController then, only the NSString propertys are accesible. As soon as i stry to access propertys of VCardNItem, vCardADRitem or vCardTELitem, i get an EXC_BAD_ACCESS Error.
Looks like the Objects within the vcardItem Object are not available !?
I've set the NSZombie... thing, my vcardItem Object is still living (No "Zombie"), but i cannot access the data.
any Idea? I'm a little bit stucked here....
Code Review did the job, after building in Xcode 4 against iOS 5 all is fine!

#property scope issues and memory problems

I am having a crash I do not understand. I am downloading a couple files from a remote server, and when a file has finished downloading, I am attempting to retrieve an object that was attached to the request object.
Tia for any help!
S.
Main Class
for (TrainingEntry* _entry in objects) {
HTTPRequest * request = [HTTPRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", [[ConfigLoader config] objectForKey:#"Server"], _entry.url]]];
[request setDownloadDestinationPath:[NSString stringWithFormat:#"%#/%#", documentsDirectoryPath, _entry.filename]];
[request setEntry:_entry];
[request setRaw:_entry.title];
TrainingEntry * test = (TrainingEntry*)[request _entry];
NSLog(#"title: %#", [test title]); //<= This works
NSLog(#"filename: %#", [test filename]); //<= This works
[[self networkQueue] addOperation:request];
}
// Start Queue
[[self networkQueue] go];
...
- (void)requestFinished:(HTTPRequest *)request {
if ([[self networkQueue] requestsCount] == 0) {
[self setNetworkQueue:nil];
}
NSLog(#"req: %#", [request raw]);
NSLog(#"title: %#", [[request entry] title]); // <= This works
NSLog(#"filename: %#", [[request entry] filename]); // <= This crashes
}
HTTPRequest Object
#interface HTTPRequest : ASIHTTPRequest {
}
#property (nonatomic, retain) TrainingEntry * entry;
#property (nonatomic, retain) NSString * raw;
#end
TrainingEntry Class
#interface TrainingEntry : NSObject {
NSString * title;
NSString * filename;
}
#property (nonatomic, retain) NSString * title;
#property (nonatomic, retain) NSString * filename;
Something that may be giving you trouble is not having copy in your property declaration. You should consider using copy for all objects that conform to the NSCopying protocol specification, especially NSString and other collection classes.
In the past, changing retain to copy for an NSString property solved a similar issue for me.
edit: some research
This post may help clarify why you should use copy over retain for immutable objects.
When a crash occurs, there will be a backtrace.
Post it.
Either your program will break in the debugger, and the call stack will be in the debugger UI (or you can type 'bt
With that, the cause of the crash is often quite obvious. Without that, we are left to critique the code.
If this crashes:
NSLog(#"filename: %#", [[request entry] filename]); // <= This crashes
It is either because request has been over-released and is no longer viable or because filename is returning a garbage object. Given that request worked previously, it is likely that filename has been over-released.
Where do you set filename?

Storing UIImages with ObjectiveRecord and ObjectiveSync

Does anyone know how I should go about storing a UIImage with the version of ObjectiveRecord packaged with ObjectiveSync? (Note that the version of SQLPersistantObjects in ObjectiveRecord is older than the current version) At the moment, I am attempting to store the UIImage data as NSData:
#interface Picture : SQLitePersistentObject {
NSString *pictureId;
NSDate *updatedAt;
NSData *imageData;
UIImage *image;
}
#property (nonatomic, retain) NSString *pictureId;
#property (nonatomic, retain) NSData *imageData;
#property (nonatomic, retain) NSDate *updatedAt;
I can set the data OK, and store it in the DB, but when I select a record from the DB, I get the data as a NSCFString as opposed to NSData. Does anyone know why?
If you want to store the image in the sqlite database then, the image should be stored as BLOB type in the sqlite database