I want to update data in server which runs in REST API. i am using RESTKIT from ios device. But i could not find how to use PUT in restkit.
I have to send data like key:"user_id" value:"2" these format. Can anyone please help me to solve this problem.. :(
SOKeyValue.h : serialized object used as parameter for your call.
#import <Foundation/Foundation.h>
#interface SOKeyValue : NSObject
#property (nonatomic, retain) NSString* key;
#property (nonatomic, retain) NSString* value;
#end
Here's a simplified code to initialize Restkit :
/*
This part of code must be executed only one time in your application
*/
//To see logs
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);
//Init with good domain
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:#"http://mydomain.dev/ui/v1"];
//Indicate to use JSON
[RKObjectManager sharedManager].serializationMIMEType = RKMIMETypeJSON;
//Route path when you call a PUT with SOKeyValue class
[manager.router routeClass:[SOKeyValue class] toResourcePath:#"/yourpath" forMethod:RKRequestMethodPUT];
//Serialization for SOKeyValue class
RKObjectMapping* keyvalueSerializationMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class] ];
[authSerializationMapping mapAttributes:#"key", #"value", nil];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:keyvalueSerializationMapping forClass:[SOKeyValue class] ];
Now we can implement a service who use PUT. In the object that will implement the call dont forget the restkit delegate RKObjectLoaderDelegate:
#import <Foundation/Foundation.h>
#import <RestKit/RestKit.h>
#import "SOKeyValue.h"
#interface MyViewOrMyServiceObject: NSObject <RKObjectLoaderDelegate>
- (void)putKeyValue;
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects;
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error;
#end
In your (.m) :
- (void)putKeyValue
{
SOKeyValue *keyvalue = [[SOKeyValue alloc] init];
keyvalue.key = #"k";
keyvalue.value = #"2";
[[RKObjectManager sharedManager] putObject:keyvalue delegate:self];
[keyvalue release];
}
You can see status code in your trace, and use callback functions :
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects;
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error;
So i dont have MAC at home, it's diffcult for help you about the code structure. If you have questions do not hesitate.
Related
I am developing an application through which user can share images.Using php file I am uploading file on the server and downloading using php file.when i download file it is take bit long time.How do i make it little bit fast.
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *data1 = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSArray *arrImg = [data1 componentsSeparatedByString:#"###"];
int i;
NSMutableArray *receivedUrlArr = [[NSMutableArray alloc]init];
NSString *str,*strNew,*path;
NSData *imageData;
ImagesClass *obj;
int count;
for ( i=0; i<[arrImg count]-1; i++) {
[receivedUrlArr addObject:[arrImg objectAtIndex:i]];
str = [NSString stringWithFormat:#"http:////receive_images/%#",[receivedUrlArr objectAtIndex:i]];
strNew = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
UIImage *myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strNew]]];
obj = [[ImagesClass alloc]init];
obj.imageId = i+1;
obj.imageName = [[arrImg objectAtIndex:i] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
obj.thumbImage = myImage;
[[DBModel database]inserttoReceivedList:obj receiverMobNo:mobileno];
path = [RECEIVEDIMAGE_DIR stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",obj.imageName]];
imageData = UIImagePNGRepresentation(obj.thumbImage);
[imageData writeToFile:path atomically:YES];
}
}
Thanks in advance.
No matter how efficient your method for storing an image is, you will always be bottlenecked by the speed of the connection.
However, you seem to be going about this the wrong way. -connection:didReceiveData is for receiving data incrementally. It seems that you are assuming that once you receive the data, you have finished loading the image, then doing a complicated bit of processing to save the partially downloaded image. Instead, your delegate for NSURLConnection should implement -connectionDidFinishLoading. In this method, you will convert the concatenated data to an image and save it then.
Here is how I would set things up:
Let's assume you have a controller class that is displaying images/needs to download more images.
Now, create a class named something like "ImageDownloader" which implements NSURLConnection Delegate. When you initialize this class, you will provide it with an image name and a URL to the image that needs to be downloaded. Within ImageDownloader, you will need an NSMutableData property. Finally, you will need a method such as -startDownload to get things moving.
-startDownload should first make sure that your NSMutableData property is empty and initialized. Once that's done, you can start the NSURLConnection's download. Be sure to set the delegate to your instance of ImageDownloader. In -connection:didReceiveData, append the data that is received to your NSMutableData property. In -connectionDidFinishLoading, convert that NSMutableData property to an image and save it using the image's name that your controller provided. From there, let the controller instance know the image is saved through a delegate method call or a notification.
Hope this helps.
edit: IIRC, Apple provides some sample code called "ImageDownloader" which is pretty similar if this explanation is confusing.
I have developed a class called File Downloader which is depicted as below :
Step 1 : Create a "FileDownloader.h" and add this in it.
#import <Foundation/Foundation.h>
#protocol fileDownloaderDelegate <NSObject>
#optional
- (void)downloadProgres:(NSNumber*)percent forObject:(id)object;
#required
- (void)downloadingStarted;
- (void)downloadingFinishedFor:(NSURL *)url andData:(NSData *)data;
- (void)downloadingFailed:(NSURL *)url;
#end
#interface FileDownloader : NSObject
{
#private
NSMutableURLRequest *_request;
NSMutableData *downloadedData;
NSURL *fileUrl;
id <fileDownloaderDelegate> delegate;
double totalFileSize;
}
#property (nonatomic, strong) NSMutableURLRequest *_request;
#property (nonatomic, strong) NSMutableData *downloadedData;
#property (nonatomic, strong) NSURL *fileUrl;
#property (nonatomic, strong) id <fileDownloaderDelegate> delegate;
- (void)downloadFromURL:(NSString *)urlString;
#end
Step 2 : Create a "FileDownloader.m" and write following
#import "FileDownloader.h"
#implementation FileDownloader
#synthesize _request, downloadedData, fileUrl;
#synthesize delegate;
- (void)downloadFromURL:(NSString *)urlString
{
[self setFileUrl:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
self._request = [NSMutableURLRequest requestWithURL:self.fileUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0f];
NSURLConnection *cn = [NSURLConnection connectionWithRequest:self._request delegate:self];
[cn start];
}
#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if([delegate respondsToSelector:#selector(downloadingStarted)])
{
[delegate performSelector:#selector(downloadingStarted)];
}
totalFileSize = [response expectedContentLength];
downloadedData = [NSMutableData dataWithCapacity:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[downloadedData appendData:data];
if([delegate respondsToSelector:#selector(downloadProgres:forObject:)])
{
[delegate performSelector:#selector(downloadProgres:forObject:) withObject:[NSNumber numberWithFloat:([downloadedData length]/totalFileSize)] withObject:self];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if([delegate respondsToSelector:#selector(downloadingFailed:)])
{
[delegate performSelector:#selector(downloadingFailed:) withObject:self.fileUrl];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if([delegate respondsToSelector:#selector(downloadingFinishedFor:andData:)])
{
[delegate performSelector:#selector(downloadingFinishedFor:andData:) withObject:self.fileUrl withObject:self.downloadedData];
}
}
#end
Step 3 : Now Import "#import "FileDownloader.h"" in your viewcontroller and "fileDownloaderDelegate" Delegate in .h file
Step 4 : Create Object , Set Delegate and URL to Download file.
FileDownloader *objDownloader = [[FileDownloader alloc] init];
[objDownloader setDelegate:self];
[objDownloader downloadFromURL:#"yourURL"];
Step 5 : Dont forget to implement Delegate methods in your view controller to get notify about download progress. enjoy..
SUBJECT: Core Data, can't retrieve/set to my properties from VC's. Most common mistake?
Searched through this site but could not quite get the answered I need (many good tips though), so thought I post this question in hope it will resolve my issue I've had for a couple of weeks now! Yes, very frustrating, you probably know the feeling! So ANY help would be great - thank's! :-)
Oveview:
iOS 5.1 project. Got Core Data working (tested in main.h/NSLog) but I'm having trouble retrieving and setting Entities properties (data) from other view controllers. Xcode recognizes my singelton "AppContent" found in the AppDelegate from other view controllers, but not the entity name and it's properties.
What is the most common mistake regarding this?
I get a feeling of that I've just missed to importing some file in the right place etc...
Some more details;
FYI: I'm trying to use a recommended method by Matt Campell, that creates a singleton in the AppDelegate that can be used all over the app to work with the managedObjectContext from any view controllers, and retrieve and save data to Core Data and it's entities and it's respective properties. This is done by importing the following two files to the app;
appContent.h
#import <Foundation/Foundation.h>
#import "Contest.h" // Root Entity in CD model
#import "Player.h"
#interface AppContent : NSObject
+(AppContent *)sharedContent;
#property(strong, readonly) id rootObject;
-(void)save;
-(void)rollback;
#end
appContent.m
#import "AppContent.h"
#import <CoreData/CoreData.h>
#interface AppContent()
-(NSURL *)dataStoreURL;
#property (nonatomic, strong, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, strong, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, strong, readonly) NSManagedObjectContext *managedObjectContext;
#end
#implementation AppContent
NSManagedObjectModel *_managedObjectModel;
NSPersistentStoreCoordinator *_persistentStoreCoordinator;
NSManagedObjectContext *_managedObjectContext;
id _rootObject;
static AppContent *singletonInstance = nil;
+ (AppContent *)sharedContent{
#synchronized(self){
if (singletonInstance == nil)
singletonInstance = [[self alloc] init];
return(singletonInstance);
}
}
- (NSURL *)dataStoreURL {
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
return [NSURL fileURLWithPath:[docDir stringByAppendingPathComponent:#"DataStore.sql"]];
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel) {
return _managedObjectModel;
}
_managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator) {
return _persistentStoreCoordinator;
}
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:[self dataStoreURL]
options:nil
error:&error]) {
NSLog(#"Unresolved Core Data error with persistentStoreCoordinator: %#, %#", error, [error userInfo]);
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext *)managedObjectContext {
if (_managedObjectContext) {
return _managedObjectContext;
}
if ([self persistentStoreCoordinator]) {
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
}
return _managedObjectContext;
}
-(id)rootObject{
if(_rootObject)
return _rootObject;
// #warning Replace [CHANGE] with your root object entity name
NSString *entityName = #"Contest";
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName
inManagedObjectContext:context];
request.entity = entity;
NSArray *listOfObjects = [context executeFetchRequest:request
error:nil];
if([listOfObjects count] == 1){
_rootObject = [listOfObjects lastObject];
return _rootObject;
}
_rootObject = [NSEntityDescription insertNewObjectForEntityForName:entityName
inManagedObjectContext:context];
// Adding some testdata (only first time...)
// Contest
Contest *c = _rootObject;
c.name = #"Big Game 1";
// Players
Player *p1 = (Player *) [NSEntityDescription insertNewObjectForEntityForName:#"Player"
inManagedObjectContext:context];
p1.name = #"Player One";
[c addPlayersObject:p1];
Player *p2 = (Player *) [NSEntityDescription insertNewObjectForEntityForName:#"Player"
inManagedObjectContext:context];
p2.name = #"Player Two";
[c addPlayersObject:p2];
[self save];
return _rootObject;
}
-(void)save{
NSError *error = nil;
NSManagedObjectContext *context = [self managedObjectContext];
if([context hasChanges])
[context save:&error];
if(error)
NSLog(#"Warning: Error saving to data store. %#", error);
}
-(void)rollback{
NSManagedObjectContext *context = [self managedObjectContext];
if([context hasChanges])
[context rollback];
}
#end
Here are the model files (created by CD model editor);
Contest.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class Player;
#interface Contest : NSManagedObject
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSSet *players;
#end
#interface Contest (CoreDataGeneratedAccessors)
- (void)addPlayersObject:(Player *)value;
- (void)removePlayersObject:(Player *)value;
- (void)addPlayers:(NSSet *)values;
- (void)removePlayers:(NSSet *)values;
#end
Contest.m
#import "Contest.h"
#import "Player.h"
#implementation Contest
#dynamic name;
#dynamic players;
#end
Player.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class Contest;
#interface Player : NSManagedObject
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) Contest *contests;
#end
Player.m
#import "Player.h"
#import "Contest.h"
#implementation Player
#dynamic name;
#dynamic contests;
#end
Here is a view controller
Trying to get hold of the Core Data Entities and it properties here, but Xcode see's the appContent but don't recognize it and when building it gives error "Can't find property player"...
contestPlayerVC.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "AppContent.h"
#interface contestPlayerVC : UIViewController
#property (strong, nonatomic) IBOutlet UITextField *playerNameField;
#property (strong, nonatomic) IBOutlet UITextField *playerMailField;
#property (strong, nonatomic) IBOutlet UIButton *playerSaveButton;
#property (weak, nonatomic) AppContent *content;
// Test
// #property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
- (IBAction)playerChooseImage:(UIButton *)sender;
- (IBAction)dismissModal:(UIButton *)sender;
- (IBAction)hideKeyboard:(id)sender;
- (IBAction)playerSave:(UIButton *)sender;
#end
contestPlayerVC.m
Not showing hole file since problem is in the method viewDidLoad...
#import "contestPlayerVC.h"
#interface contestPlayerVC ()
#end
#implementation contestPlayerVC
#synthesize playerNameField, playerMailField, playerSaveButton, content;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// Call 1 - seems to work ok
self.content = [AppContent sharedContent];
////// Call 2 - gives error, can't find property "player" - WHY?
// Trying to set textfield to CD Entity "Player" and it's property "name"
self.playerNameField.text = self.content.player.name;
NSLog(#"Player is: %#", self.content.player.name);
// Call 3 - works ok
NSLog(#"Content is: %#", self.content.description);
}
...
Any tips or suggestions? Thanks! :-)
Btw: Sorry about the long post, I'm not sure about how else describe my problem well enough for anyone to understand it. If you read it all - I'm impressed and I'll be real happy to if you help me solve this. Probably some basic thing I totally missed. Thank's ;-)
#user1578933 Ok, let's back up a second and think about what each piece is responsible for:
Contest is the root (first) object responsible for everything related to a contest including the name and list of players
Player is responsible for everything about a player including the player's name
AppContent is responsible for managing the object graph (retrieving the object graph so you can use it and remembering what the user adds and removes)
contestPlayerVC is responsible for presenting content (from AppContent)
In your app, everything starts with Contest. In your AppContent implementation you have code that generates that property rootObject and this is where the Contest object is created for the first time.
NOTE You have that defined as id because you are copying this code directly for our program, but you could also have defined rootObject as type Contest like this:
-(Contest *) rootObject;
This your point of entry to your object graph. The idea is that you will access AppContent (using the Singleton pattern) and then retrieve the Contest object. The Contest object will have the NSSet object collection that contains references to each player in the collection.
Here's an example of how you would use this in your view controller:
- (void)viewDidLoad {
[super viewDidLoad];
self.content = [AppContent sharedContent];
//get reference to the root object contest
Contest *theContest = (Contest *)self.content.rootObject;
//get an array based reference to the players in theContest
NSArray *players = [theContest.players allObjects];
//Example of getting a reference to an individual player:
Player *p1 = [players objectAtIndex:0];
}
This is essentially how you would add this content to your view controller; for a table view controller you would use the index path row property to find out what player goes in what table view cell (see cellForRowAtIndexPath).
#user1578933 - after reading this post and also the ones you left on Mobile App Mastery Institute it seems like you are missing some understanding of the object graph and how all these object relationships are organized in general. I've recently added some additional content about how to use and think about the Objective-C object graph here. Also, I would carefully look over the sections on Objective-C, Table Views and Core Data again.
Your error, not being able to find a player property on self.content, is because your AppContent class doesn't declare any property of that name. Let's walk through your code one line at a time:
self.content = [AppContent sharedContent];
Now self.content is an object of type AppContent, and so any future calls to self.content.something will look for visible methods or properties declared on that class (usually in "AppContent.h").
self.playerNameField.text = self.content.player.name;
We're looking here for a property named player in an AppContent object, which has as its header:
#import <Foundation/Foundation.h>
#import "Contest.h" // Root Entity in CD model
#import "Player.h"
#interface AppContent : NSObject
+(AppContent *)sharedContent;
#property(strong, readonly) id rootObject;
-(void)save;
-(void)rollback;
#end
Nowhere in there is a #property named player - you have a rootObject property, and you import the "Player.h" header, but you never declare the property you're trying to access. You'll need to add a line like:
#property(strong) Player * player;
and either #synthesize it in your "AppContent.m" file, or provide the appropriate accessor methods to back that property.
Iam getting an EXC_BAD_ACCESS all the time and I cannot figure out why...
Simple task:
The Parser Class pases XML with touchXML in an NSMutableArray called listArray.
In the Method grabCountry I can access the listArray and listArray.count works well.
Now I need the listArray.count in another Class the MasterViewController.
But Im getting an EXC_BAD_ACCESS error all the time.
Please help!
Here is the code snipplet:
Parser.h
#import <Foundation/Foundation.h>
#interface Parser : NSObject
#property (strong, retain) NSMutableArray *listArray;
#property (strong, retain) NSURL *url;
-(void) grabCountry:(NSString *)xmlPath;
#end
Parser.m
#import "Parser.h"
#import "TouchXML.h"
#implementation Parser
#synthesize listArray;
#synthesize url;
-(void) grabCountry:(NSString *)xmlPath {
// Initialize the List MutableArray that we declared in the header
listArray = [[NSMutableArray alloc] init];
// Convert the supplied URL string into a usable URL object
url = [NSURL URLWithString: xmlPath];
//XML stuff deleted
// Add the blogItem to the global blogEntries Array so that the view can access it.
[listArray addObject:[xmlItem copy]];
//works fine
NSLog(#"Amount: %i",listArray.count);
}
#end
MasterViewController.h
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "TouchXML.h"
#import "Parser.h"
#class Parser;
#interface MasterViewController : UITableViewController{
Parser *theParser;
}
#end
MasterViewControlelr.m
- (void)viewDidLoad
{
NSString *xmlPath = #"http://url/to/xml.xml";
theParser = [[Parser alloc] init];
//Starts the parser
[theParser grabCountry:xmlPath];
//Here I want to access the Array count, but getting an BAD ACCESS error
NSLog(#"Amount %#",[theParser.listArray count]);
[super viewDidLoad];
}
Can anyone explain me what the problem here is?
Thanks!
Internally, each #property has a corresponding instance variable.
In your -grabCountry method, you are directly accessing the instance variable in the statement listArray = [[NSMutableArray alloc] init]; (same with url = [NSURL URLWithString: xmlPath];), instead of the #property's setter method, causing the NSMutableArray that you alloc-init'd to not be retained by the property. To invoke the #property's setter method, you should call
NSMutableArray *temp = [[NSMutableArray alloc] init];
self.listArray = temp; // or [self setListArray:temp];
[temp release];
If you want to have Xcode show an error when you are directly accessing the instance variable of an #property, you can have #synthesize listArray = _listArray, which changes the name of the instance variable to _listArray.
Generally, if there is an alloc-init, there must be a corresponding release (except if using Automatic Reference Counting).
Also, in the [listArray addObject:[xmlItem copy]]; statement, the call to copy is not needed, as NSArrays retain every object that is added to them. Calling copy also increases the retain count, which is another leak. Instead, you should just have [self.listArray addObject:xmlItem];
You are getting EXC_BAD_ACCESS because in NSLog(#"Amount %#",[theParser.listArray count]);, you are using %# format specifier, which is for NSStrings. You want to print the array's count, an integer, so you should be using %d or %i.
Hoping to get a little push in the right direction. I am having trouble getting a nested object to serialize properly when I POST to my rails app using RestKit. I have the following mappings:
RKObjectMapping *cartSerializationMapping = [RKObjectMapping mappingForClass:[TOCart class]];
[cartSerializationMapping mapKeyPath:#"place.placeID" toAttribute:#"order[external_id]"];
//map the line items serialization mapping
RKObjectMapping *lineItemSerializationMapping = [RKObjectMapping mappingForClass:[TOLineItem class]];
[lineItemSerializationMapping mapKeyPath:#"itemID" toAttribute:#"itemID"];
[lineItemSerializationMapping mapKeyPath:#"name" toAttribute:#"name"];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:lineItemSerializationMapping forClass:[TOLineItem class]];
//add relationship bw line items to TOLineItem
[cartSerializationMapping mapKeyPath:#"line_items" toRelationship:#"order[line_items]" withMapping:lineItemSerializationMapping serialize:YES];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:cartSerializationMapping forClass:[TOCart class]];
After posting to the server, serialization works for the parent object but not for the nested line_item object:
Started POST "/orders" for 127.0.0.1 at 2011-11-16 04:05:58 -0800
Processing by OrdersController#create as JSON
Parameters: {"order"=>{"line_items"=>["<TOLineItem: 0x8aafdb0>"], "external_id"=>"4ae8a535f964a52024b121e3"}}
I want the line_item to serialize to itemID and name etc...
Did I set my mappings incorrectly?
Thanks!
UPDATE:
My TOCart class:
#import <Foundation/Foundation.h>
#class TOPlace;
#interface TOCart : NSObject
{
NSNumber *cartID;
TOPlace *place; //post to external id
NSString *state;
NSMutableArray *line_items;
}
#property (nonatomic, retain) NSNumber *cartID;
#property (nonatomic, retain) TOPlace *place;
#property (nonatomic, retain) NSString *state;
#property (nonatomic, retain) NSMutableArray *line_items;
#end
I always define my mapping to map from API to entities & then create the serialization mapping with [myMappingFromApi inverseMapping] selector. You can find further details in my answer to somewhat different question, but definitely related: RestKit: How does one post an array of objects?.
I am trying to launch the App Store without launching Safari with all the redirects and I am getting an error about "Request for member 'iTunesURL' in something not a structure or union."
I am new to a lot of this so thank you for being patient with me. I think it has something to do with me calling "self.iTunesURL" since it doesn't think iTunesURL is a part of the current class, but I could be very wrong.
Thank you in advance for your help while I am (slowly) learning all of this.
SampleAppDelegate.h
-(void)launchStore:(NSURL *)iTunesURL;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;
SampleAppDelegate.m
// Process a LinkShare/TradeDoubler/DGM URL to something iPhone can handle
- (void)launchStore:(NSURL *)iTunesURL {
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:iTunesURL] delegate:self startImmediately:YES];
[conn release];
}
// Save the most recent URL in case multiple redirects occur
// "iTunesURL" is an NSURL property in your class declaration
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
self.iTunesURL = [response URL];
return request;
}
// No more redirects; use the last URL saved
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[[UIApplication sharedApplication] openURL:self.iTunesURL];
}
MyViewController.h
#import "SampleAppDelegate.h"
and i have NSURL *iTunesURL; within the #interface curley braces.
#property (nonatomic, retain) NSURL *iTunesURL;
- (IBAction) proButtonPressed: (id)sender; // press to launch App Store
MyViewController.m
#import "MyViewController.h"
#implementation MyViewController
#synthesize iTunesURL;
- (IBAction) proButtonPressed: (id) sender {
NSURL *iTunesLink = [NSURL URLWithString:#"actual http URL goes here"];
SampleAppDelegate *appDelegate = (SampleAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate launchStore:iTunesLink];
}
iTunesURL is a property of the ViewController class and you can only use the self reference within the methods of that class. Importing the ViewController.h class doesn't give the SampleAppDelegate class the ability to call the properties of ViewController class unless it is a subclass of ViewController.
You need to create a new another property within SampleAppDelegate and assign the value of ViewController.iTunesURL to that property.