RestKit with Three20 Integration - iphone

I'm trying to work with Restkit to call my web server api, but things are not working.
My controller just show the activity indicator and nothing happens.
I have an api call which suppose to return the top 50 videos ,for example:
http://example.com/services/getTop50Video
The return is in the format of :
<results>
<mysql_host>72.9.41.97</mysql_host>
<results>
<title/>
<views/>
<video_id>j2xFxHgENt4</video_id>
<thumbnail>http://img.youtube.com/vi/j2xFxHgENt4/2.jpg</thumbnail>
<url/>
</results>
...
</results>
My App delegate Code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Configure RestKit Object Manager
RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:#"http://example.com/services"];
RKObjectMapper* mapper = objectManager.mapper;
[mapper registerClass:[YouTubeVideo class] forElementNamed:#"video"];
// Other non relevant stuff
}
TWYouTubeVideo Class :
#implementation TWYouTubeVideo
#synthesize title = _title;
#synthesize numberOfViews = _numberOfViews;
#synthesize videoID = _videoID;
#synthesize thumbnailURL = _thumbnailURL;
+ (NSDictionary*)elementToPropertyMappings {
return [NSDictionary dictionaryWithKeysAndObjects:
#"title", #"title",
#"views", #"numberOfViews",
#"video_id", #"videoID",
#"thumbnail", #"thumbnailURL",
nil];
}
My Controller code :
-(id) initWithResourcePath:(NSString*) requestedResourcePath
{
if (self = [super init])
{
self.resourcePath = requestedResourcePath;
}
return self;
}
- (void)createModel {
self.model = [[[RKRequestTTModel alloc] initWithResourcePath:self.resourcePath] autorelease];
}
- (void)didLoadModel:(BOOL)firstTime {
[super didLoadModel:firstTime];
RKRequestTTModel* model = (RKRequestTTModel*)self.model;
NSMutableArray* items = [NSMutableArray arrayWithCapacity:[model.objects count]];
for (YouTubeVideo* video in model.objects) {
TableSubtitleItem *item = [TableSubtitleItem itemWithText:video.title
subtitle:[NSString stringWithFormat:#"%# views", video.numberOfViews]
imageURL:video.thumbnailURL
defaultImage:[YouTubeVideo defaultThumbnail]
URL:nil
accessoryURL:nil];
[items addObject:item];
}
// Ensure that the datasource's model is still the RKRequestTTModel;
// Otherwise isOutdated will not work.
TTListDataSource* dataSource = [TTListDataSource dataSourceWithItems:items];
dataSource.model = model;
self.dataSource = dataSource;
}
And pushing the Controller:
SecondYouTubeController* viewController = [[SecondYouTubeController alloc] initWithResourcePath:#"/getTop50VideoXML?json=true"];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
First, I guess I need to somehow tell the parser that the video objects appear inside a "response" node.
Second, I'm not sure I'm doing all the calls as should.
I would really appreciate help here.

You can drill down into the "responses" element by setting the keyPath property on your RKRequestTTModel to "responses".
Is your response actually XML? Currently RestKit doesn't support XML payloads (it's on the roadmap to get working again). Can you get a JSON payload? If not, and you feel like fighting the good fight, all you need to do is implement the RKParser protocol that can turn XML to/from Cocoa objects (Dictionaries and Arrays).

I found this question looking to get XML working with RestKit 0.20.
At the time of the answer above it wasn't possible - it now is via an additional module:
https://github.com/RestKit/RKXMLReaderSerialization
You can make use of it by adding this to your Podfile:
pod 'RKXMLReaderSerialization', :git => 'https://github.com/RestKit/RKXMLReaderSerialization.git', :branch => 'master'
And registering it for use thus:
[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:#"application/xml"];

Related

NSBlockOperation or NSOperation with ALAsset Block to display photo-library images using ALAsset URL

I am asking this question regarding my questions Display photolibrary images in an effectual way iPhone and Highly efficient UITableView "cellForRowIndexPath" method to bind the PhotoLibrary images.
So I would like to request that answers are not duplicated to this one without reading the below details :)
Let's come to the issue,
I have researched detailed about my above mentioned issue, and I have found the document about operation queues from here.
So I have created one sample application to display seven photo-library images using operation queues through ALAsset blocks.
Here are the sample application details.
Step 1:
In the NSOperationalQueueViewController viewDidLoad method, I have retrieved all the photo-gallery ALAsset URLs in to an array named urlArray.
Step 2:
After all the URLs are added to the urlArray, the if(group != nil) condition will be false in assetGroupEnumerator, so I have created a NSOperationQueue, and then created seven UIImageView's through a for loop and created my NSOperation subclass object with the corresponding image-view and URL for each one and added them in to the NSOperationQueue.
See my NSOperation subclass here.
See my implementation (VierwController) class here.
Let's come to the issue.
It not displaying all the seven images consistently. Some of the images are missing. The missing order is changing multiple times (one time it doesn't display the sixth and seventh, and another time it doesn't display only the second and third). The console log displays Could not find photo pic number. However, the URLs are logged properly.
You can see the log details here.
Are there any mistakes in my classes?
Also, when I go through the above mentioned operational queue documentation, I have read about NSBlockOperation. Do I need to implement NSBlockOperation instead of NSOperation while dealing with ALAsset blocks?
The NSBlockOperation description says
A class you use as-is to execute one or more block objects
concurrently. Because it can execute more than one block, a block
operation object operates using a group semantic; only when all of the
associated blocks have finished executing is the operation itself
considered finished.
How can I implement the NSBlockOperation with ALAsset block regarding my sample application?
I have gone through Stack Overflow question Learning NSBlockOperation. However, I didn't get any idea to implement the NSBlockOperation with ALAsset block!!
This is the tutorial about "How to access all images from iPhonePhoto Library using ALAsset Library and show them on UIScrollView like iPhoneSimulator" .
First of all add AssetsLibrary.framework to your project.
Then in your viewController.h file import #import <AssetsLibrary/AssetsLibrary.h> header file.
This is your viewController.h file
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "AppDelegate.h"
#interface ViewController : UIViewController <UIScrollViewDelegate>
{
ALAssetsLibrary *assetsLibrary;
NSMutableArray *groups;
ALAssetsGroup *assetsGroup;
// I will show all images on `UIScrollView`
UIScrollView *myScrollView;
UIActivityIndicatorView *activityIndicator;
NSMutableArray *assetsArray;
// Will handle thumbnail of images
NSMutableArray *imageThumbnailArray;
// Will handle original images
NSMutableArray *imageOriginalArray;
UIButton *buttonImage;
}
-(void)displayImages;
-(void)loadScrollView;
#end
And this is your viewController.m file -
viewWillAppear:
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation ViewController
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
assetsArray = [[NSMutableArray alloc]init];
imageThumbnailArray = [[NSMutableArray alloc]init];
imageOriginalArray = [[NSMutableArray alloc]init];
myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 416.0)];
myScrollView.delegate = self;
myScrollView.contentSize = CGSizeMake(320.0, 416.0);
myScrollView.backgroundColor = [UIColor whiteColor];
activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.center = myScrollView.center;
[myScrollView addSubview:activityIndicator];
[self.view addSubview:myScrollView];
[activityIndicator startAnimating];
}
viewDidAppear:
-(void)viewDidAppear:(BOOL)animated
{
if (!assetsLibrary) {
assetsLibrary = [[ALAssetsLibrary alloc] init];
}
if (!groups) {
groups = [[NSMutableArray alloc] init];
}
else {
[groups removeAllObjects];
}
ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {
//NSLog(#"group %#",group);
if (group) {
[groups addObject:group];
//NSLog(#"groups %#",groups);
} else {
//Call display Images method here.
[self displayImages];
}
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
NSString *errorMessage = nil;
switch ([error code]) {
case ALAssetsLibraryAccessUserDeniedError:
case ALAssetsLibraryAccessGloballyDeniedError:
errorMessage = #"The user has declined access to it.";
break;
default:
errorMessage = #"Reason unknown.";
break;
}
};
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:listGroupBlock failureBlock:failureBlock];
}
And this is displayImages: method body
-(void)displayImages
{
// NSLog(#"groups %d",[groups count]);
for (int i = 0 ; i< [groups count]; i++) {
assetsGroup = [groups objectAtIndex:i];
if (!assetsArray) {
assetsArray = [[NSMutableArray alloc] init];
}
else {
[assetsArray removeAllObjects];
}
ALAssetsGroupEnumerationResultsBlock assetsEnumerationBlock = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
[assetsArray addObject:result];
}
};
ALAssetsFilter *onlyPhotosFilter = [ALAssetsFilter allPhotos];
[assetsGroup setAssetsFilter:onlyPhotosFilter];
[assetsGroup enumerateAssetsUsingBlock:assetsEnumerationBlock];
}
//Seprate the thumbnail and original images
for(int i=0;i<[assetsArray count]; i++)
{
ALAsset *asset = [assetsArray objectAtIndex:i];
CGImageRef thumbnailImageRef = [asset thumbnail];
UIImage *thumbnail = [UIImage imageWithCGImage:thumbnailImageRef];
[imageThumbnailArray addObject:thumbnail];
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef originalImage = [representation fullResolutionImage];
UIImage *original = [UIImage imageWithCGImage:originalImage];
[imageOriginalArray addObject:original];
}
[self loadScrollView];
}
Now you have two array one is imageThumbnailArray and another is imageOriginalArray.
Use imageThumbnailArray for showing on UIScrollView for which your scrolling will not be slow.... And use imageOriginalArray for an enlarged preview of image.
'loadScrollView:' method, This is how to images on UIScrollView like iPhoneSimulator
#pragma mark - LoadImages on UIScrollView
-(void)loadScrollView
{
float horizontal = 8.0;
float vertical = 8.0;
for(int i=0; i<[imageThumbnailArray count]; i++)
{
if((i%4) == 0 && i!=0)
{
horizontal = 8.0;
vertical = vertical + 70.0 + 8.0;
}
buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonImage setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
[buttonImage setTag:i];
[ buttonImage setImage:[imageThumbnailArray objectAtIndex:i] forState:UIControlStateNormal];
[buttonImage addTarget:self action:#selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
[myScrollView addSubview:buttonImage];
horizontal = horizontal + 70.0 + 8.0;
}
[myScrollView setContentSize:CGSizeMake(320.0, vertical + 78.0)];
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
}
And here you can find which image button has been clicked -
#pragma mark - Button Pressed method
-(void)buttonImagePressed:(id)sender
{
NSLog(#"you have pressed : %d button",[sender tag]);
}
Hope this tutorial will help you and many users who search for the same.. Thank you!
You have a line in your DisplayImages NSOperation subclass where you update the UI (DisplayImages.m line 54):
self.imageView.image = topicImage;
This operation queue is running on a background thread, and we know that you should only update the state of the UI on the main thread. Since updating the view of an image view is definitely updating the UI, this can be simply fixed by wrapping the call with:
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = topicImage;
});
This puts an asynchronous call on the main queue to update the UIImageView with the image. It's asynchronous so your other tasks can be scheduled in the background, and it's safe as it is running on the main queue - which is the main thread.

SAFELY_RELEASE in ViewDidUnLoad

is there any difference between the two methods?
```
// MACRO FUNCTION
#define SAFELY_RELEASE(__POINTER) { [__POINTER release]; __POINTER = nil; }
// C FUNCTION
void SAFELY_RELEASE(id __POINTER) {
[__POINTER release]; __POINTER = nil;
}
```
Yes. The function won't do what you expect it to, because the pointer will have been passed into it by value, rather than by reference.
Imagine this:
- (void)method {
id object = [[NSObject alloc] init];
SAFELY_RELEASE( object );
}
SAFELY_RELEASE gets object. It can send it messages, but setting it to nil will not change its value in method.
An equivalent function would be:
void SAFELY_RELEASE(id *__POINTER) {
[*__POINTER release]; *__POINTER = nil;
}
Then you'd use it by using:
SAFELY_RELEASE( &object );
The macro has another downside, though: Xcode's refactoring tools will probably not be able to change the parameter inside. For instance:
#interface Foo {
NSObject *var;
}
#implementation Foo
- (id)init {
if (( self = [super init] )) {
var = [[NSObject alloc] init];
}
return self;
}
- (void)dealloc {
SAFELY_RELEASE(var);
[super dealloc];
}
If you try to rename var using the refactor tool, you'll probably find that it won't be able to rename the var in dealloc.
Really, unless you have a really good reason to do this you should be using ARC.
void SAFELY_RELEASE(id __POINTER) is guaranted to __POINTER be an releasable object.
Both of them is wrong, because __POINTER = nil; will have no effects. You should nil it in object (controller)
I was using one of these macros, then I cam across this post.
Makes sense that you don't want to set to nil while in development as you want it to crash on a dealloc reference and not sending it to nil.

how to stop creating object Instance when its not need

The class do have
-(void) trackByPage : (NSString*) pageName {
TrackPage *track_p;
= [[TrackPage alloc] init];
track_p.page1 = #"welcome";
track_p.page2= self.String1;
[track_p release];
}
I am accessing from controller class this method.
- (void)viewDidLoad {
[super viewDidLoad];
TrackPageMeasurement *trackPage_Measurement = [[TrackPageMeasurement alloc]init];
[trackPage_Measurement trackByPage:#"Msg"];
[trackPage_Measurement release];
}
- (void)selectedDataValue {
TrackPageMeasurement *trackPage_Measurement = [[TrackPageMeasurement alloc]init];
[trackPage_Measurement trackByPage:#"DataValue"];
[trackPage_Measurement release];
}
I am accessing that through another class. trackByPage. by passing string ..
Each time i am accessing each time object instance is created how to stop those thing.
selectedDataValue shouldn't be calling [super viewDidLoad]; The code doesn't exactly inspire me with confidence; it looks to me more like that you want to retrieve some tracking object rather than creating a new one each time. Do you know what a singleton is?
Using a singleton would look more like:
TrackPage *track_p = [TrackPage instance];
track_p.page1 = #"welcome";
track_p.page2 = self.String1;
How about
TrackPage *track_p;
if(track_p==nil)
{
track_p= [[TrackPage alloc] init];
track_p.page1 = #"welcome";
track_p.page2= self.String1;
}
[track_p release];

Dropbox Api in iphone

I am trying to integrate dropbox with iphone and done with login option.I want to load folders and files on root path in table view just after login.
code for this is
- (void)viewWillAppear:(BOOL)animated {
[self.restClient loadMetadata:#"/"];
}
This loadMetadata is method in DBRestClient.m class.I managed to print json value on console
Code is
- (void)parseMetadataWithRequest:(DBRequest*)request {
NSAutoreleasePool* pool = [NSAutoreleasePool new];
NSDictionary* result = (NSDictionary*)[request resultJSON];
DBMetadata* metadata = [[[DBMetadata alloc] initWithDictionary:result] autorelease];
[self performSelectorOnMainThread:#selector(didParseMetadata:) withObject:metadata waitUntilDone:NO];
NSLog(#"Meta data is :%#",result);
[pool drain];
}
How could I use this result value in my view controller to display this in tableview?
Get the contents of a directory and put them into an array.
- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata
{
for (DBMetadata* child in metadata.contents)
{
if (child.isDirectory)
{
[self.restClient loadMetadata:child.path withHash:hash];
}
else
{
if ( [self.directory isEqualToString:#"a directory"] ) {
/* child.path is the file, so put it into an array */
}
}
}
}
Than load your array into your UITableView as you would any other NSArray / NSMutableArray

Problem initializing an object with init in Objective-C

I have an object that i intalize it's propertis with call to an init function, it works fine,
when i tried to add another object and intalize it the first object didn't get the properites, how do i initalize it to more then one object with diffrent or the same properties?
- (void)viewDidLoad {
pic1 = [[peopleAccel alloc] init];
}
Class peopleAccel:
- (id) init
{
self = [super init];
if (self != nil) {
position = CGPointMake(100.0, 100.0);
velocity = CGPointMake(4.0, 4.0);
radius = 40.0;
bounce = -0.1f;
gravity = 0.5f;
dragging = NO;
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
acceleratedGravity = CGPointMake(0.0, gravity);
}
return self;
}
I see a problem with setting the delegate of sharedAccelerometer. Only one object can be a delegate of another object at a time. So you should create only one peopleAccel object.
EDIT:
If you need to send accelerometer events to more than one object, you can create a specific delegate object in charge of receiving accelerometer events and broadcasting them to your several peopleAccel objects via notifications. See this question for some hints: NSNotificationCenter vs delegation?
Create a proxy so multiple objects can receive accelerometer events.
Whether you should do this or use NSNotificationCenter is debatable and there are two camps, but personally I would use this approach. NSNotificationCenter has to check string names to recognise event type; this kind of approach could be ever so slightly faster especially with a bit more optimisation. A bit more typing but I would say also easier for someone else to follow.
Something like this...
/* PLUMBING */
/* in headers */
#protocol MyAccelSubDelegate
-(void)accelerometer:(UIAccelerometer*)accelerometer
didAccelerate:(UIAcceleration*)acceleration;
#end
#interface MyAccelSubDelegateProxy : NSObject <UIAccelerometerDelegate> {
NSMutableArray subDelegates;
}
-(id)init;
-dealloc;
-(void)addSubDelegate:(id<MyAccelSubDelegate>)subDelegate;
-(void)removeSubDelegate:(id<MyAccelSubDelegate>)subDelegate;
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
(UIAcceleration *)acceleration;
#end
/* in .m file */
#implementation MyAccelSubDelegateProxy
-(id)init { self = [super init];
if (self!=nil) subDelegates = [[NSMutableArray alloc] init]; return self; }
-dealloc { [subDelegates release]; }
-(void)addSubDelegate:(id<MyAccelSubDelegate>)subDelegate {
[subDelegates insertObject:subDelegate atIndex:subDelegates.count]; }
-(void)removeSubDelegate:(id<MyAccelSubDelegate>)subDelegate {
for (int c=0; c < subDelegates.count; c++) {
id<MyAccelSubDelegate> item = [subDelegates objectAtIndex:c];
if (item==subDelegate) { [subDelegates removeObjectAtIndex:c];
c--; continue; }
}
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
(UIAcceleration *)acceleration {
for (int c=0; c < subDelegates.count; c++)
[((id<MyAccelSubDelegate>)[subDelegates objectAtIndex:c])
accelerometer:accelerometer didAccelerate:acceleration];
}
#end
/* SOMEWHERE IN MAIN APPLICATION FLOW STARTUP */
accelProxy = [[MyAccelSubDelegateProxy alloc] init];
[UIAccelerometer sharedAcclerometer].delegate = accelProxy;
[UIAccelerometer sharedAcclerometer].updateInterval = 0.100; // for example
/* TO ADD A SUBDELEGATE */
[accelProxy addSubDelegate:obj];
/* TO REMOVE A SUBDELEGATE */
[accelProxy removeSubDelegate:obj];
/* SOMEWHERE IN MAIN APPLICATION SHUTDOWN */
[UIAccelerometer sharedAcclerometer].delegate = nil;
[accelProxy release];