NSURLConnection in NSOperation - objective-c

I am writing a code that reads data from a http connection and stores in a byte array.
I have written my own NSOperation class. Reference of the code is
Concurrent Operations Demystified
My HttpWorker class declaration is like
#interface HttpWorker : NSOperation{
NSString *param;
double requestCode;
BOOL isLive;
long initSleep;
BOOL _isFinished;
BOOL _isExecuting;
NSURL *_url;
NSURLConnection *_connection;
NSData *_data;
}
#property (nonatomic, retain) NSString *param;
#property (nonatomic) double requestCode;
#property (nonatomic) BOOL isLive;
#property (nonatomic) long initSleep;
#property (readonly) BOOL isFinished;
#property (readonly) BOOL isExecuting;
#property (readonly, copy) NSURL *url;
#property (nonatomic, retain) NSURLConnection *httpCon;
#property (readonly, retain) NSData *data;
-(id)initWithUrl:(NSURL *)_url;
-(void) setRequestParameters:(NSString *)parameters iRequestCode:(double)iRequestCode initialSleep:(long)initialSleep;
#end
And my HttpWorker.m class is like
#import "HttpWorker.h"
#import "Resources.h"
#implementation HttpWorker
#synthesize param;
#synthesize requestCode;
#synthesize isLive;
#synthesize initSleep;
#synthesize isFinished = _isFinished;
#synthesize isExecuting = _isExecuting;
#synthesize url = _url;
#synthesize data = _data;
-(id) initWithUrl: (NSURL *)Url{
self = [super init];
if(self == nil){
return nil;
}
_url = [Url copy];
_isExecuting = NO;
_isFinished = NO;
return self;
}
-(BOOL) isConcurrent{
return YES;
}
-(void) start{
if(![NSThread isMainThread]){
[self performSelectorOnMainThread:#selector(start) withObject:nil waitUntilDone:NO];
return;
}
[self willChangeValueForKey:#"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:#"isExecuting"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:_url];
NSLog(#"Connecting... %#",_url);
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately: YES];
if(_connection == nil){
NSLog(#"connection is nil");
}
}
-(void) setRequestParameters:(NSString *)parameters iRequestCode:(double)iRequestCode initialSleep:(long)initialSleep {
self.param = parameters;
self.requestCode = iRequestCode;
self.initSleep = initialSleep;
}
/////////////////////////// delegate methods ///////////////////////////////
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"receieved response...");
_data = [[NSData alloc] init];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)incomingData {
NSLog(#"receieved data...");
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"connection did finish loading...");
}
#end
Problem is that when i run this code and add httpworker object to the NSOperationQueue, the code runs successfully and _connection is not nil but none of the delegate methods is executed. Can anyone please help?
Thanks and Best Regards...

Your delegate for the connection is "self" (= your NSOperation object). I assume this object is already gone when the connection wants to send messages to the delegate.
Your NSOperation does not have a "main" implementation. Consequently nothing will happen after the thread is started. It will (asynchronously!) fire the NSOperation and quit.
See:
http://developer.apple.com/mac/library/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html#//apple_ref/occ/instm/NSOperation/main
Bottom line: I highly recommend ASIHTTPRequest for this kind of task.
http://allseeing-i.com/ASIHTTPRequest/

Related

Parsing JSON with AFHTTPClient

I'm using the AFNetworking library to parse json using the AFHTTPClient. I can verify that the json is being parsed within the client block and send that data to my json model. However, when I try to access the json model from outside the block I get no data. How can I pass the parsed json data to the json model then access that model data elsewhere in the app?
the AFHTTPClient subclass / singleton:
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#interface JsonClient : AFHTTPClient
+ (JsonClient *)sharedClient;
#end
#import "JsonClient.h"
#import "AFJSONRequestOperation.h"
static NSString *const kJsonBaseURLString = #"https://alpha-api.app.net/";
#implementation JsonClient
+ (JsonClient *)sharedClient {
static JsonClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[JsonClient alloc] initWithBaseURL:[NSURL URLWithString:kJsonBaseURLString]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:#"Accept" value:#"application/json"];
return self;
}
#end
the JSON model data:
#import <Foundation/Foundation.h>
#interface TheJson : NSObject
#property (nonatomic, copy) NSString *createdAt;
#property (nonatomic, copy) NSString *userText;
- (id)initWithDictionary:(NSDictionary *)dict;
#end
#import "TheJson.h"
#implementation TheJson
- (id)initWithDictionary:(NSDictionary *)dict {
self = [super init];
if (self) {
self.createdAt = [dict objectForKey:#"created_at"];
self.userText = [dict objectForKey:#"text"];
}
return self;
}
#end
the ViewController to update the user interface:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#end
#import "ViewController.h"
#import "JsonClient.h"
#import "TheJson.h"
#interface ViewController ()
#property (weak) IBOutlet UILabel *createdLabel;
#property (weak) IBOutlet UILabel *textLabel;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)fetchJsonData:(id)sender {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[[JsonClient sharedClient] getPath:#"stream/0/posts/stream/global" parameters:nil
success:^(AFHTTPRequestOperation *operation, id JSON) {
NSArray *postsFromResponse = [JSON valueForKeyPath:#"data"];
NSDictionary *dictFromArray = postsFromResponse[0];
TheJson *jsonObject = [[TheJson alloc] initWithDictionary:dictFromArray];
NSLog(#"createdAt is %#", jsonObject.createdAt);
NSLog(#"text from user is %#", jsonObject.userText);
[self updateInterface];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error is %#", [error description]);
}
];
}
- (void)updateInterface {
TheJson *thejson;
[_createdLabel setText:thejson.createdAt];
[_textLabel setText:thejson.userText];
}
#end
You haven't passed the new jsonObject out of the block nor stored it anywhere. A short term answer is to declare updateInterface to take the jsonObject as a parameter.
So your updateInterface becomes updateInterface: something like this:
- (void)updateInterface:(TheJson*)thejson {
[_createdLabel setText:thejson.createdAt];
[_textLabel setText:thejson.userText];
}
...and then within your block, you call this method like this:
[self updateInterface:jsonObject];
Longer term, if your app has many of these objects and/or needs to hold onto them for any amount of time, you probably want to think about how you will store and organize these as you download them.

Issue Connecting with GCDAsyncSocket with OSX executable

I have the excellent GCDAsyncSocket running perfectly on an iOS app I have developed.
I was just playing around with setting up a Mac OSX command line program that uses the library in a similar way to log to SQLite DB but can't get it to even attempt to connect to host. No errors get generated. The program doesn't crash or anything so don't have an idea about why it's not working. Does anyone have an idea why this won't work?
The console only prints out the following (with no connect/disconnect/read/write logging i.e. the socket delegate methods are not being called):
Attempting to connect to host: 192.168.1.2 on port: 1234 to refresh
Here is quite a bit of the code I am using:
main.m
#import <Foundation/Foundation.h>
#import "LoggerClass.h"
int main(int argc, const char * argv[]) {
#autoreleasepool {
LoggerClass *logger = [[LoggerClass alloc] init];
[logger startLogging];
while (logger.status == 0) {
sleep(1);
continue;
}
return 0;
}
}
LoggerClass.h
#import <Foundation/Foundation.h>
#import "Device.h"
#interface LoggerClass : NSObject <DeviceProtocol>
#property (nonatomic, strong) FMDatabase *database;
#property (nonatomic, strong) NSArray *devices;
#property (nonatomic) int status;
- (void)startLogging;
#end
LoggerClass.m
#import "LoggerClass.h"
#import "FMDatabase.h"
#define kLoggingInProgress 0
#define kLoggingCompleted 1
#implementation LoggerClass
#synthesize database = _database;
#synthesize devices = _devices;
#synthesize status = _status;
- (id)init {
if (self = [super init]) {
self.status = kLoggingInProgress;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *path = [docsPath stringByAppendingPathComponent:#"database.sqlite"];
self.database = [FMDatabase databaseWithPath:path];
Device *d1 = [Device deviceWithName:#"Device 1" address:#"192.168.1.2" delegate:self];
self.devices = [NSArray arrayWithObjects:d1, nil];
}
return self;
}
- (void)startLogging {
for (Device *d in self.devices) {
[d refresh];
}
}
- (void)didUpdateDevice:(Device *)device {
// Insert DB entry code
NSLog(#"%# has finished Logging", device.name);
self.status = kLoggingCompleted; // This would obviously register completed if only 1 device returned but for sake of this test that fine
}
#end
Device.h
#import <Foundation/Foundation.h>
#import "GCDAsyncSocket.h"
#protocol DeviceProtocol;
#interface Device : NSObject
#property (nonatomic, weak) id<DeviceProtocol> delegate;
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSString *address;
#property (nonatomic, strong) GCDAsyncSocket *socket;
+ (Device *)deviceWithName:(NSString *)n address:(NSString *)a delegate:(id<DeviceProtocol>)d;
- (void)refresh;
#end
#protocol DeviceProtocol <NSObject>
#required
- (void)didUpdateDevice:(Device *)device;
#end
Device.m
#import "Device.h"
#define DEVICE_PORT 1234
#implementation Device
#synthesize delegate = _delegate;
#synthesize name = _name;
#synthesize address = _address;
#synthesize socket = _socket;
- (id)initWithName:(NSString *)name andAddress:(NSString *)address andDelegate:(id<DeviceProtocol>)delegate { // Designated Initialiser
if (self = [super init]) {
self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
self.name = name;
self.address = address;
self.delegate = delegate;
}
return self;
}
+ (Device *)deviceWithName:(NSString *)n address:(NSString *)a delegate:(id<DeviceProtocol>)d {
return [[Device alloc] initWithName:n andAddress:a andDelegate:d];
}
#pragma mark - GCD Async Socket Delegate Methods
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port {
NSLog(#"Connected to: %#", self.address);
}
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)error {
NSLog(#"Socket for %# disconnected %#.", self.address, error);
if (self.delegate) [self.delegate didUpdateDevice:self];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag {
NSLog(#"socket:didWriteDataWithTag:");
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSLog(#"socket:didReadData:withTag:");
[self.socket disconnect];
}
- (void)refresh {
if ([self.address length] == 0) { [self.delegate didUpdateDevice:self]; return; }
NSLog(#"Attempting to connect to host: %# on port: %i to refresh", self.address, DEVICE_PORT);
NSError *error = nil;
if (![self.socket connectToHost:self.address onPort:DEVICE_PORT withTimeout:15 error:&error]) NSLog(#"ERROR: %#", error);
NSData *dataToSend;
// Build byte data here to send to device (exact same data works on iOS)
[self.socket writeData:dataToSend withTimeout:10 tag:0];
[self.socket readDataWithTimeout:-1 tag:0];
}
#end
I just re-read your comment and realized what your main() looks like. I think that's where your problem lies. The callbacks are probably sitting in the main dispatch queue but it never gets a chance to execute them. In a Cocoa application, the main queue normally runs as part of the main run loop, but you aren't starting a run loop.
See the dispatch_get_main_queue() documentation.
I think the simplest initial fix is to replace your spin loop with this:
dispatch_main();

Pass NSArrays from ViewController to NSObject class

I have a single view application where the ViewController contains a UIView of custom class CPTGraphHostingView so that it holds a CorePlot graph. The content of that UIView is managed by an NSObject sub-class called SimpleScatterPlot. This SimpleScatterPlot object holds all the parameters needed to configure the graph (axis ranges, labels, number of points, etc.)
ViewController.h
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#import "SimpleScatterPlot.h"
#interface ViewController : UIViewController
{
IBOutlet CPTGraphHostingView *_graphHostingView;
SimpleScatterPlot *_scatterPlot;
NSMutableData *dataConexion;
}
#property (nonatomic,strong) NSArray *valor;
#property (nonatomic,strong) NSArray *strAnoMes;
#property (nonatomic,strong) NSArray *indicador;
#property (nonatomic, retain) SimpleScatterPlot *scatterPlot;
#end
In ViewController.m I have some methods to initialise a few arrays from some JSON data:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize indicador,valor,strAnoMes;
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *urlString = #"http://xxxx/ios/datosgrafica.php";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
dataConexion = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[dataConexion appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
indicador = [NSJSONSerialization JSONObjectWithData:dataConexion options:nil error:nil];
// ARRAYS OF INTEREST
strAnoMes = [indicador valueForKey:#"StrAnoMes"];
valor = [indicador valueForKey:#"Valor"];
self.scatterPlot = [[SimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:pointArray];
[self.scatterPlot initialisePlot];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
In the SimpleScatterPlot.m I would like to use the array "valor" to configure axis ranges, and I would like to use the array "strAnoMes" to draw custom labels in the xAxis.
What do I have to do so that I can pass those arrays defined in ViewController to SimpleScatterPlot?
I have tried to #import "ViewController.h" but it gives me errors. Any other ideas? What is the best way to approach this situation?
You can take two properties in SimpleScatterPlot.
SimpleScatterPlot.h
#property (nonatomic, retain) NSArray * strAnoMes;
#property (nonatomic, retain) NSArray * valor;
SimpleScatterPlot.m
#synthesize strAnoMes;
#synthesize valor;
In ViewController.m, After creating scatterPlot in connectionDidFinishLoading:, assign the values to above properties as below.
self.scatterPlot.strAnoMes = strAnoMes;
self.scatterPlot.valor = valor;
One way to do this is to create a simple data object and pass it directly into your SimpleScatterPlot object:
Data Object:
#interface SimpleScatterPlotData : NSObject
#property (...) NSArray *valor;
#property (...) NSArray *strAnoMes;
#end
#implementaton SimpleScatterPlotData
#synthesize valar;
#synthesize strAnoMes;
-(void)dealloc
{
...
...
[super dealloc];
}
#end
Implement a load method in your SimpleScatterPlot class:
#interface SimpleScatterPlot
-(void)loadData:(SimpleScatterPlotData *)data;
#end
#implementation SimpleScatterPlot
-(void)loadData:(SimpleScatterPlotData *)data
{
NSArray *valor = data.valor;
NSArray *strAnoMes = data.strAnoMes;
/*
Do something
*/
}
#end
Then in your ViewController class:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
indicador = [NSJSONSerialization JSONObjectWithData:dataConexion options:nil error:nil];
// ARRAYS OF INTEREST
strAnoMes = [indicador valueForKey:#"StrAnoMes"];
valor = [indicador valueForKey:#"Valor"];
SimpleScatterPlotData *data = [[[SimpleScatterPlotData alloc] init] autorelease];
data.valor = valor;'
data.strAnoMes = strAnoMes;
self.scatterPlot = [[SimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:pointArray];
[self.scatterPlot loadData:data];
}
You could also change your current initializer or add a new initializer to your SimpleScatterPlot class so that you pass those arrays in when you alloc the object. So your the call to your initializer would look something like:
self.scatterPlot = [[SimpleScatterPlot alloc] initWithHostingView:_graphHostingView andData:pointArray andValor:valor andstrAnoMes:strAnoMes];
Then in your initializer you can set the object properties to those passed in values.

unable to import yahoo contacts in ios app getting BadExcess error

I have downloaded this project from https://github.com/yahoo/yos-social-objc .
I have changed the ConsumerKey,
ConsumerSecret
and ApplicationId but When I Run the app it crashes. It gives an error of BAD-Excess.
Does anyone has any idea of this??
please advise
Thanks
Basically its just downloaded project from yahoo's developer's page still.
This is my Complete code
SocialSampleAppDelegate.h file
#import <UIKit/UIKit.h>
#import "YOSSession.h"
#class SocialSampleViewController;
#interface SocialSampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
SocialSampleViewController *viewController;
YOSSession *session;
NSMutableDictionary *oauthResponse;
BOOL launchDefault;
}
#property BOOL launchDefault;
#property (nonatomic, readwrite, retain) YOSSession *session;
#property (nonatomic, readwrite, retain) NSMutableDictionary *oauthResponse;
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet SocialSampleViewController *viewController;
- (void)getUserProfile;
- (void)createYahooSession;
- (void)handlePostLaunch;
#end
SocialSampleAppDelegate.m
#import "SocialSampleAppDelegate.h"
#import "SocialSampleViewController.h"
#import "YOSUser.h"
#import "YOSUserRequest.h"
#import "NSString+SBJSON.h"
#implementation SocialSampleAppDelegate
#synthesize window;
#synthesize viewController;
#synthesize session;
#synthesize launchDefault;
#synthesize oauthResponse;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
launchDefault = YES;
[self performSelector:#selector(handlePostLaunch) withObject:nil afterDelay:0.0];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
launchDefault = NO;
if (!url) {
return NO;
}
NSArray *pairs = [[url query] componentsSeparatedByString:#"&"];
NSMutableDictionary *response = [NSMutableDictionary dictionary];
for (NSString *item in pairs) {
NSArray *fields = [item componentsSeparatedByString:#"="];
NSString *name = [fields objectAtIndex:0];
NSString *value = [[fields objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[response setObject:value forKey:name];
}
self.oauthResponse = response;
[self createYahooSession];
return YES;
}
- (void)handlePostLaunch
{
if(self.launchDefault) {
[self createYahooSession];
}
}
- (void)createYahooSession
{
// create session with consumer key, secret and application id
// set up a new app here: https://developer.yahoo.com/dashboard/createKey.html
// because the default values here won't work
self.session = [YOSSession sessionWithConsumerKey:#"MYConsumer KEy"
andConsumerSecret:#"MY Secret"
andApplicationId:#"My APPID"];
if(self.oauthResponse) {
NSString *verifier = [self.oauthResponse valueForKey:#"oauth_verifier"];
[self.session setVerifier:verifier];
}
BOOL hasSession = [self.session resumeSession];
if(!hasSession) {
[self.session sendUserToAuthorizationWithCallbackUrl:nil];
} else {
[self getUserProfile];
}
}
- (void)getUserProfile
{
// initialize the profile request with our user.
YOSUserRequest *userRequest = [YOSUserRequest requestWithSession:self.session];
// get the users profile
[userRequest fetchProfileWithDelegate:self];
}
- (void)requestDidFinishLoading:(YOSResponseData *)data
{
NSDictionary *userProfile = [[data.responseText JSONValue] objectForKey:#"profile"];
// NSLog(#"%#",[userProfile description]);
if(userProfile) {
[viewController setUserProfile:userProfile];
}
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
SocialSampleViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
[nicknameLabel setText:#"loading..."];
}
- (void)setUserProfile:(NSDictionary *)data
{
NSString *welcomeText = [NSString stringWithFormat:#"Hey %# %#!",
[[data objectForKey:#"profile"] objectForKey:#"givenName"],
[[data objectForKey:#"profile"] objectForKey:#"familyName"]];
[nicknameLabel setText:welcomeText];
}
info plist

Error with loading data without internet connection (Restkit)

After making the rest call through RKObjectManager,it is not loading the objects when i don't have internet connection. I test with domain.local and my WIFI is Off.
I know that i can implement with "reachabilityObserver" but i don't know how can i make this.
My code :
#import "ViewInformationForm.h"
#import <RestKit/RestKit.h>
#interface User : NSObject {
NSNumber* _user_forfait;
NSNumber* _user_client_free;
NSNumber* _user_demande_portabilite;
NSNumber* _user_mail_confirm;
NSNumber* _user_mail_enregistrement_inscrption;
NSNumber* _user_mail_depart_expedition;
NSNumber* _user_mail_arrivee_expedition;
NSNumber* _user_activation;
NSNumber* _user_portabilite;
}
#property (nonatomic, retain) NSNumber* user_forfait;
#property (nonatomic, retain) NSNumber* user_client_free;
#property (nonatomic, retain) NSNumber* user_demande_portabilite;
#property (nonatomic, retain) NSNumber* user_mail_confirm;
#property (nonatomic, retain) NSNumber* user_mail_enregistrement_inscrption;
#property (nonatomic, retain) NSNumber* user_mail_depart_expedition;
#property (nonatomic, retain) NSNumber* user_mail_arrivee_expedition;
#property (nonatomic, retain) NSNumber* user_activation;
#property (nonatomic, retain) NSNumber* user_portabilite;
#end
#implementation User
#synthesize user_forfait = _user_forfait;
#synthesize user_client_free = _user_client_free;
#synthesize user_demande_portabilite = _user_demande_portabilite;
#synthesize user_mail_confirm = _user_mail_confirm;
#synthesize user_mail_enregistrement_inscrption = _user_mail_enregistrement_inscrption;
#synthesize user_mail_depart_expedition = _user_mail_depart_expedition;
#synthesize user_mail_arrivee_expedition = _user_mail_arrivee_expedition;
#synthesize user_activation = _user_activation;
#synthesize user_portabilite = _user_portabilite;
#end
#implementation ViewInformationForm;
#synthesize picker,pickerDate, forfaitNames;
#synthesize forfaitText, TextDateEnregistrement;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)LoadData {
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[User class]];
[mapping mapKeyPathsToAttributes:
#"data.user_forfait", #"user_forfait",
#"data.user_client_free", #"user_client_free",
#"data.user_demande_portabilite", #"user_demande_portabilite",
#"data.user_mail_confirm", #"user_mail_confirm",
#"data.user_mail_enregistrement_inscrption", #"user_mail_enregistrement_inscrption",
#"data.user_mail_depart_expedition", #"user_mail_depart_expedition",
#"data.user_mail_arrivee_expedition", #"user_mail_arrivee_expedition",
#"data.user_activation", #"user_activation",
#"data.user_portabilite", #"user_portabilite",
nil];
RKObjectManager *objectManager = [RKObjectManager sharedManager];
NSString* urlUID = [NSString stringWithFormat:#"/user/data?uid=%#",uuid];
RKObjectLoader *objectLoader = [objectManager objectLoaderWithResourcePath:urlUID delegate:self];
objectLoader.method = RKRequestMethodGET;
objectLoader.objectMapping = mapping;
[objectLoader send];
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
User* user = [objects objectAtIndex:0];
NSString* info = [NSString stringWithFormat:
#"\n user_forfait : %# \n"
#"user_client_free : %#",[user user_forfait], [user user_client_free]];
NSLog(#"%#",info);
}
- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
RKLogError(#"Load of RKRequest %# failed with error: %#", objectLoader, error);
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[RKObjectManager objectManagerWithBaseURL:gRKCatalogBaseURL];
[self LoadData];
[super viewDidLoad];
self.forfaitNames = [[NSArray alloc] initWithObjects:
#"-- Sélectionnez un forfait --", #"Forfait 19,99 €", #"Forfait 15,90 €", #"Forfait 2 €",
#"Forfait 0 €", nil];
}
Error :
2012-01-24 09:59:32.120 Free M. Stats[13438:10703] I restkit:RKLog.m:30 RestKit initialized...
2012-01-24 09:59:32.127 Free M. Stats[13438:10703] I restkit.network.reachability:RKReachabilityObserver.m:369 Network availability has been determined for reachability observer <RKReachabilityObserver: 0x8987300 host=0.0.0.0 isReachabilityDetermined=YES isMonitoringLocalWiFi=652464 reachabilityFlags=-R tc----->
2012-01-24 09:59:32.129 Free M. Stats[13438:10703] E restkit.network:RKRequest.m:464 Failed to send request to http://freemobile-stats.local/user/data?uid=b070b4f0a581cf1a16312b7bbb31353c due to unreachable network. Reachability observer = <RKReachabilityObserver: 0x8987300 host=0.0.0.0 isReachabilityDetermined=YES isMonitoringLocalWiFi=652464 reachabilityFlags=-R tc----->
2012-01-24 09:59:32.130 Free M. Stats[13438:10703] E app:ViewInformationForm.m:102 Load of RKRequest <RKObjectLoader: 0x6e69050> failed with error: Error Domain=org.restkit.RestKit.ErrorDomain Code=2 "The client is unable to contact the resource at http://freemobile-stats.local/user/data?uid=b070b4f0a581cf1a16312b7bbb31353c" UserInfo=0x6c99270 {NSLocalizedDescription=The client is unable to contact the resource at http://freemobile-stats.local/user/data?uid=b070b4f0a581cf1a16312b7bbb31353c}
Thank you for your help.
AO.
This is how you register for the reachability notifications in RestKit:
// Register for changes in network availability
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:#selector(reachabilityDidChange:) name:RKReachabilityDidChangeNotification object:nil];
And here you catch the notification:
- (void)reachabilityDidChange:(NSNotification *)notification {
RKReachabilityObserver* observer = (RKReachabilityObserver *) [notification object];
RKReachabilityNetworkStatus status = [observer networkStatus];
if (RKReachabilityNotReachable == status) {
RKLogInfo(#"No network access!");
} else if (RKReachabilityReachableViaWiFi == status) {
RKLogInfo(#"Online via WiFi!");
} else if (RKReachabilityReachableViaWWAN == status) {
RKLogInfo(#"Online via Edge or 3G!");
}
}
You don't even have to register to Restkit reachability notifications system because it is already implemented in the RKRequest method.
So, if no internet connection is detected, your request will fail and this delegate (that you may have already implemented) is called :
- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error {
// No internet !
}
Beware, this delegate can also be called for others reasons, like when there is an error in the mapping of your data. But for simple cases it should be ok for what you want to do !
Obviously, it won't load data from the Internet if there's no Iternet connection. You may want to try one of the pre-implemented Reachability classes, for example: http://developer.apple.com/library/ios/#samplecode/Reachability/Listings/Classes_Reachability_h.html#//apple_ref/doc/uid/DTS40007324-Classes_Reachability_h-DontLinkElementID_5