uploadedFile not called - ios

I have an app where I upload a simple .csv file to Dropbox. The files upload perfectly when I send them, but the restClient uploadedFile method is not called. I would like this to use this to display to the user that the file has been uploaded successfully. I seem to remeber it was called the first few times I ran the code, but then it stopped and I can't see why.
Here are some snippets:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) //Cancel
{
}
else if (buttonIndex == 1) //Send
{
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *CCD = [docPath stringByAppendingPathComponent:#"CCD.csv"];
if ([[NSFileManager defaultManager] fileExistsAtPath:CCD])
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *machineName = [defaults objectForKey:#"machineName"];
NSString *fileTitle = [defaults stringForKey:#"setTitle"];
NSMutableString *filePath = [NSMutableString string];
[filePath appendString:docPath];
[filePath appendString:#"/CCD.csv"];
NSString *destDir = #"/";
[SVProgressHUD showWithStatus:[NSString stringWithFormat:#"Sending to %#...", machineName]];
[[self restClient] uploadFile:fileTitle toPath:destDir
withParentRev:nil fromPath:filePath];
}
}
}
- (void)restClient:(DBRestClient*)restClient uploadedFile:(NSString*)filePath {
NSLog(#"File uploaded successfully");
[SVProgressHUD dismiss];
};
As I said, it uploads the file perfectly, I just don't get the call to the uploadedFile method.

Try this way..
#interface ResultClass_vice : UIViewController<DBRestClientDelegate>
{
DBRestClient *restClient;
}
#pragma mark - DropBox
- (void)didPressLink {
// [[DBSession sharedSession]unlinkAll];
if (![[DBSession sharedSession] isLinked]) {
[[DBSession sharedSession] linkFromController:self];
// Session must be linked before creating any DBRestClient objects.
// nstr
UIAlertView *al=[[UIAlertView alloc]initWithTitle:#"" message:#"You must have to Login" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[al show];
[al release];
}
}
- (DBRestClient *)restClient {
if (!restClient) {
restClient =
[[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
restClient.delegate = self;
}
return restClient;
}
- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
//NSLog(#"File uploaded successfully to path: %#", metadata.path);
UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:#"Success" message:#"Your file is successfully uploaded to Dropbox" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil]retain];
[alert show];
[alert release];
}
- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error {
NSLog(#"File upload failed with error - %#", error);
}
Let me know if you have any problem because I already implemented it.

The main problem is you have changed upload method parameters:
You are using:
- (void)restClient:(DBRestClient*)restClient uploadedFile:(NSString*)filePath {
NSLog(#"File uploaded successfully to path: %#", metadata.path);
}
And you should used:
- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
NSLog(#"File uploaded successfully to path: %#", metadata.path);
}
If you change the number of parameters, you are creating a new function, and therefore, Dropbox SDK will not called it.
I hope this would be helpful

Related

Integrate iCloud into ios App and Retrieve files from iCloud

I integrated iCloud into iOS app using raywenderlich https://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1
But iam unable to show all the files from iCloud to our iOS app and also need specific type of files like pdf, doc and docx
Can any one suggest me.
Follow below steps to integrate iCloud in iOS app and retrieve files.
1. Enable iCloud from your developer account.
2. Create iCloud containers entitlement at developer account.
3. Then just use below code where you want to integrate your iCloud integration.
First of all import #import and add iCloudDelegate delegate then set delegate:
// Setup iCloud
[[iCloud sharedCloud] setDelegate:self];
[[iCloud sharedCloud] setVerboseLogging:YES];
[[iCloud sharedCloud] setupiCloudDocumentSyncWithUbiquityContainer:nil];
[self showiCloudFiles];
then implementation of method showiCloudFiles below
-(void) showiCloudFiles{
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
else if ([[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == NO) {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"iCloud Disabled", #"You have disabled iCloud for this app. Would you like to turn it on again?");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
UIAlertAction* deleteButton = [UIAlertAction actionWithTitle:#"Turn On iCloud"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"userCloudPref"];
[[NSUserDefaults standardUserDefaults] synchronize];
BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:#"userCloudPref"] == YES) {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:#[#"public.content"]
inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
[self presentViewController:documentPicker animated:YES completion:nil];
}
}];
[alert addAction:deleteButton];
[self presentViewController:alert animated:YES completion:nil];
} else {
UIAlertController * alert = SIMPLE_ALERT_VIEW(#"Setup iCloud", #"iCloud is not available. Sign into an iCloud account on this device and check that this app has valid entitlements.");
UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:#"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
}];
[self presentViewController:alert animated:YES completion:nil];
}
}
After that for downloading file use UIDocumentPickerDelegate method:
#pragma mark - UIDocumentPickerDelegate
-(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
if (controller.documentPickerMode == UIDocumentPickerModeImport) {
//NSLog(#"%#",url);
[url startAccessingSecurityScopedResource];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent]; NSString *fileExtension = [newURL pathExtension]; if([fileExtension isEqualToString:#"zip"]) {if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"pages"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"numbers"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"key"] ) {
// Remove .zip if it is an iWork file
fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
}
NSError *fileConversionError;fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
// Do further code using fileData
}
}];
[url stopAccessingSecurityScopedResource];
}
}
For UIDocumentPicker visit this link iOS-8-UIDocumentPicker
Follow this guide
https://www.raywenderlich.com/12779/icloud-and-uidocument-beyond-the-basics-part-1
Download sample code at
https://github.com/rwenderlich/PhotoKeeper
Check if iCloud available
- (void)initializeiCloudAccessWithCompletion:(void (^)(BOOL available)) completion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_iCloudRoot = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (_iCloudRoot != nil) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud available at: %#", _iCloudRoot);
completion(TRUE);
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"iCloud not available");
completion(FALSE);
});
}
});
}
Query type of flies like pdf, doc and docx
- (NSMetadataQuery *)documentQuery {
NSMetadataQuery * query = [[NSMetadataQuery alloc] init];
if (query) {
// Search documents subdir only
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
// Add a predicate for finding the documents
NSString * filePattern = [NSString stringWithFormat:#"*.%#", PTK_EXTENSION];
[query setPredicate:[NSPredicate predicateWithFormat:#"%K LIKE %#",
NSMetadataItemFSNameKey, filePattern]];
}
return query;
}

Navigation in iOS using Objective-C

i have an ios app which uses a login page and after authenticating it enters into the inbox page.But after entering the inbox page it comes back automatically to the login page
Login.m
{
if ([username length] == 0 || [password length] == 0)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Oops!"
message:#"Make sure you enter a username and password!"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else
{
NSString *query = [NSString stringWithFormat:#"SELECT * FROM Login_Info WHERE username='%#'",username]; // Execute the query.
NSLog(#" query = %#", query );
// Get the results.
if (self.arrLogin_Info != nil) {
self.arrLogin_Info = nil;
}
self.arrLogin_Info = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
[def setObject:[self.arrLogin_Info objectAtIndex:0] forKey:#"idKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:1] forKey:#"usernameKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:2] forKey:#"passwordKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:3] forKey:#"emailKey"];
NSLog(#" query output = %#", self.arrLogin_Info);
NSString *val = [self.arrLogin_Info objectAtIndex:2];
// NSLog(#" val = %#",val);
if ([val isEqualToString:password] )
{
// NSLog(#" Inside if before entering app");
[self.navigationController popToRootViewControllerAnimated:YES];
}
else
{
//NSLog(#" Inside else before entering app");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry!"
message:#"Please ensure you have entered the correct password!"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}
}
#end
Inbox.m
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
id u = [def objectForKey:#"idkey"];
if(u)
{
NSString *query = [NSString stringWithFormat:#"Select *from Messages where recipient_ID=%#",u];
self.msg = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
// [self.tableView reloadData];
}
else
{
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
// [self.tableView reloadData];
}
- (IBAction)logout:(id)sender {
//[PFUser logOut];
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"showLogin" ])
{
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
}
}
Your Inbox view controller uses the presence of an object for the key 'idkey' in NSUserDefaults to determine whether the user is already logged in, or whether to show the login screen.
I presume that this line in login.m
[def setObject:[self.arrLogin_Info objectAtIndex:0] forKey:#"idKey"];
is supposed to be setting that key, but you don't show where you initialise def - so my guess is that this is nil and you aren't saving the data in NSUserDefaults.
Also, all of this -
if (self.arrLogin_Info != nil) {
self.arrLogin_Info = nil;
}
self.arrLogin_Info = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
can be simplified to this
self.arrLogin_Info = [self.dbManager loadDataFromDB:query];

I want to use identifiers in .m in other .m (implementation file import) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
On cameraviewcontrolle.mr I take a picture or movie using UIImagePickerController. On completion, I call back to aanvraagviewcontroller.m.
I want to save the the picture by tapping on send button.
My question comes to this I think, how can I import .m file or take the picture/movie to aanvraagviewcontroller.m (I use Parse.com to save my PFObjects)?
This is cameraviewcontroller.m
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
// A photo was taken/selected!
self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the image!
UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil);
}
}
else {
// A video was taken/selected!
self.videoFilePath = (__bridge NSString *)([[info objectForKey:UIImagePickerControllerMediaURL] path]);
if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the video!
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(self.videoFilePath)) {
UISaveVideoAtPathToSavedPhotosAlbum(self.videoFilePath, nil, nil, nil);
}
}
}
[self uploadMessage];
[self dismissViewControllerAnimated:YES completion:nil];
[self.navigationController popToRootViewControllerAnimated:YES];}
- (void)uploadMessage {
NSData *fileData;
NSString *fileName;
NSString *fileType;
if (self.image != nil) {
UIImage *newImage = [self resizeImage:self.image toWidth:320.0f andHeight:480.0f];
fileData = UIImagePNGRepresentation(newImage);
fileName = #"image.png";
fileType = #"image";
}
else {
fileData = [NSData dataWithContentsOfFile:self.videoFilePath];
fileName = #"video.mov";
fileType = #"video";
}
PFFile *file = [PFFile fileWithName:fileName data:fileData];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:#"Please try sending your message again."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {// onderdeelAanvraag[#"file"] = file;
// onderdeelAanvraag[#"fileType"] = fileType;
// onderdeelAanvraag[#"recipientIDs"] = self.recipients;
//
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:#"Please try sending your message again."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
// Everything was successful!
[self reset];
}
// }];
}
}];
}
- (void)reset {
self.image = nil;
self.videoFilePath = nil;
[self.recipients removeAllObjects];
}
- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height {
CGSize newSize = CGSizeMake(width, height);
CGRect newRectangle = CGRectMake(0, 0, width, height);
UIGraphicsBeginImageContext(newSize);
[self.image drawInRect:newRectangle];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
This is aanvraagviewcontroller.m (when send button is pressed, i want to save the picture/movie here);
- (IBAction)verstuurAanvraag:(id)sender {
NSString *onderdeelOmschrijving = self.onderdeelOmschrijvingField.text ;
NSString *autoOmschrijving = self.autoOmschrijvingField.text ;
if ([onderdeelOmschrijving length] == 0 ||
[autoOmschrijving length] == 0)
{
UIAlertView *alertView = [[ UIAlertView alloc] initWithTitle:#"Leeg veld" message:#"Vul de lege velden in" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
}
else {
PFObject *onderdeelAanvraag = [PFObject objectWithClassName:#"Aanvragen"];
[onderdeelAanvraag setObject:[PFUser currentUser] forKey:#"Aanvrager"];
onderdeelAanvraag[#"OnderdeelOmschrijving"] = onderdeelOmschrijving;
onderdeelAanvraag[#"AutoOmschrijving"] = autoOmschrijving;
NSDate *date = [NSDate date];
onderdeelAanvraag[#"Datum"] =date;
onderdeelAanvraag[#"file"] = file;
onderdeelAanvraag[#"fileType"] = fileType;
onderdeelAanvraag[#"recipientIDs"] = self.recipients;
// Get random number between 0 and 999999
int nummer = arc4random() % 100000;
NSLog(#"nieuw nummer %d", nummer);
[onderdeelAanvraag setObject:[NSNumber numberWithInt:nummer] forKey:#"AanvraagNummer"];
[onderdeelAanvraag saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry!" message: [error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
[self performSegueWithIdentifier:#"showRecipients" sender:self];
}
}];
}
}
I SOLVED PASSING UITEXTFIELD TEXT BY THIS ;
I solved passing textfield data passing with the segue method like here ;
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"showRecipients"]){
OntvangersViewController *controller;
controller = [segue destinationViewController];
controller.onderdeelOmschrijvingField = self.onderdeelOmschrijvingField;
controller.autoOmschrijvingField = self.autoOmschrijvingField;
controller.image = self.image;
controller.videoFilePath = self.videoFilePath;
NSLog(#"videofilepath %#", self.videoFilePath);
controller.recipients = self.recipients;
}
}
Your question is muddled and confused.
The code in a .m file is not shared with other .m files.
The whole point of the C .h header file is that the header file can be shared, while the implementation (.c, or .m for Objective C) is private, and not shared.
If you want a value to be visible to another class, or another object of the same class, you should define a property in the header file.
If you want to pass a value from one view controller to another, this topic has been covered Ad nauseam here and on other forums. There are at least 2 comments on your post pointing you to other threads covering the topic.

Need suggestion to integrate gmail account in iOS developlment

I am new to iOS programming, and just want to do something fun.
I want to develop a mail client app for iPhone, it can add email accounts such as gmail and Yahoo and so on. I searched online for a while and also find some answers, before I dive into the details I just want someone who has similar experience give me some suggestions about which method is the best.
thanks
I have recently implemented gmail api to fetch gmail contacts and their email in my tableview. Gmail api is depricated, thats why you might have not got any proper documentation for that.
To implement gmail use libGDataTouchStaticLib.a library, with Gdata headers (search on google for that otherwise send me your email i will send you its zip).
The code to get gmail details are as follows
- (void)getGoogleContacts {
GDataServiceGoogleContact *service = [self contactService];
GDataServiceTicket *ticket;
BOOL shouldShowDeleted = TRUE;
// request a whole buncha contacts; our service object is set to
// follow next links as well in case there are more than 2000
const int kBuncha = 2000;
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
[query setShouldShowDeleted:shouldShowDeleted];
[query setMaxResults:kBuncha];
ticket = [service fetchFeedWithQuery:query
delegate:self
didFinishSelector:#selector(contactsFetchTicket:finishedWithFeed:error:)];
[self setContactFetchTicket:ticket];
}
- (void)setContactFetchTicket:(GDataServiceTicket *)ticket {
mContactFetchTicket = ticket;
}
- (GDataServiceGoogleContact *)contactService {
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
// update the username/password each time the service is requested
NSString *username = [txtUserName text];
NSString *password = [txtPasswrod text];
[service setUserCredentialsWithUsername:username
password:password];
return service;
}
// contacts fetched callback
- (void)contactsFetchTicket:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedContact *)feed
error:(NSError *)error {
if (error) {
NSDictionary *userInfo = [error userInfo];
NSLog(#"Contacts Fetch error :%#", [userInfo objectForKey:#"Error"]);
if ([[userInfo objectForKey:#"Error"] isEqual:#"BadAuthentication"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Authentication Failed"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Failed to get Contacts."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
} else {
NSArray *contacts = [feed entries];
NSLog(#"Contacts Count: %d ", [contacts count]);
[mutAryGoogleContacts removeAllObjects];
for (int i = 0; i < [contacts count]; i++) {
NSMutableDictionary *aDictContactDetails=[NSMutableDictionary dictionary];
GDataEntryContact *contact = [contacts objectAtIndex:i];
// Email
GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
NSString* ContactEmail = [email address];
if (ContactEmail) {
[aDictContactDetails setObject:ContactEmail forKey:#"email"];
// Name
NSString *ContactName = [[[contact name] fullName] contentStringValue];
if (ContactName) {
[aDictContactDetails setObject:ContactName forKey:#"friendName"];
}
[mutAryGoogleContacts addObject:aDictContactDetails];
}
}
//Push to next vc or do whatever you want
}
}

ios - Network / Internet Connection

After hours of searching on google I still cant find a single topic about this one:
1. I need to put error handling functions if the user does not have internet connection.
2. the user have internet connection but cant connect to the server .
And where can I put these? I tried one topic but it don't show the alert view message.
Here is my code:
- (IBAction)getDataPressed
{
if([myRequest_ isExecuting])
{
return;
}
if(myRequest_ != nil)
{
[myRequest_ release];
}
myRequest_ = [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:URL_PATH]];
myRequest_.delegate = self;
[myRequest_ startAsynchronous];
}
#pragma ASI Delegate methods
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Request finished successfully");
NSLog(#"%#",[request responseString]);
NSDictionary *responseDictionary = [[request responseString]JSONValue];
NSDictionary *arrayElement = [responseDictionary objectForKey:#"user"];
NSString *ID = [arrayElement valueForKeyPath:#"id"];
NSLog(#"id: %#",ID);
NSString *usr = [arrayElement valueForKeyPath:#"usr"];
NSLog(#"usr: %#",usr);
NSString *gd = [arrayElement valueForKeyPath:#"gd"];
NSLog(#"gd: %#",gd);
NSString *ag = [arrayElement valueForKeyPath:#"ag"];
NSLog(#"ag: %#",ag);
NSString *st = [arrayElement valueForKeyPath:#"st"];
NSLog(#"st: %#",st);
NSString *lf = [arrayElement valueForKeyPath:#"lf"];
NSLog(#"lf: %#",lf);
NSString *da = [arrayElement valueForKeyPath:#"da"];
NSLog(#"da: %d",da);
for(NSString *value in [arrayElement allValues]){
NSLog(#"Found Value %#",value);
label.text = [value stringByAppendingFormat:#",%#,%#,%#,%#,%#,%#,",ID,usr,gd,ag,st,lf];
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSLog(#"Error %#", [request error]);
if([request error])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Destination Unreachable" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
-(void) dealloc
{
[super dealloc];
}
Thanks to those who will help ^_^
I think you could try the Reachbility application to help you out checking if you have internet or not. As for the server itself, you can use the NSUrlConnection Delegate methods to check if there was a problem with your request (by seeing the kind of HTTP code that comes)

Resources