ios - Network / Internet Connection - ios

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)

Related

Unable to connect iPhone device with the ejabberd server

I am new in iOS development and try to connect my iPhone device with the ejabberd server.I follow Xmpp.org document.And also I follow this "http://code.tutsplus.com/tutorials/building-a-jabber-client-for-ios-interface-setup--mobile-7188" document thoroughly.This is a great tutorial.This help me a lot a to setup a ejabberd server in my mac and able to connect to two different application(iMessage and Adium) through ejabberd server but I am facing some problem when I started iPhone application.
First I got XMPP importing error.but I solve it, after that app crash when I use [XMPPStream addDelegate: self delegateQueue:dispatch_get_main_queue() ] method.That time Compiler says "unrecognized selector sent".so I change it to [XMPPStream addDelegate:self ].Error removed.
And at last I got alert message which told me"Can't connect to server",and finally unable to connect to the server.
I want to test client-server connection locally,so I changed server address with my Mac Ip.but still unable to connect.
please help me....If possible please suggest me how to proceed further & any other document on XMPP.
Thanks a lot.
I call this connect function when application start.
- (BOOL)connect {
[self setupStream];
NSString *jabberID = [[NSUserDefaults standardUserDefaults]stringForKey:#"userID"];
NSString *myPassword =[[NSUserDefaults standardUserDefaults] stringForKey:#"userPassword"];
if (![xmppStream isDisconnected]) {
return YES;
}
if (jabberID == nil || myPassword == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:jabberID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connect:&error]){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Can't connect to server %#", [error localizedDescription]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
[alertView release];
return NO;
}
return YES;
}
- (void)setupStream {
xmppStream = [[[XMPPStream alloc] init] autorelease];
[xmppStream addDelegate:self];
//[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence {
NSString *presenceType = [presence type]; // online/offline
NSString *myUsername = [[sender myJID] user];
NSString *presenceFromUser = [[presence from] user];
if (![presenceFromUser isEqualToString:myUsername]) {
if ([presenceType isEqualToString:#"available"]) {
[_chatDelegate newBuddyOnline:[NSString stringWithFormat:#"%##%#", presenceFromUser, #"MYSERVER"]];
} else if ([presenceType isEqualToString:#"unavailable"]) {
[_chatDelegate buddyWentOffline:[NSString stringWithFormat:#"%##%#", presenceFromUser, #"MYSERVER"]];
}
}
}
in the connect method try using these two lines also, if u are using ejabberd as mentioned in the tutorial
xmppStream.hostName = #"localhost";
xmppStream.hostPort=5222;
i was following the same tutorial and it worked for me after adding these lines..put breakpoints in the
- (void)xmppStreamDidConnect:(XMPPStream *)sender
delegate method to check if its connecting

Easier way to send JSON Data with Objective-C to PHP server?

I have a PHP RESTful server that I connect to to invoke methods based on the URL path called from my objective-c program. I use the ASIHTTPRequest and SBJson.
Everything works well but I'm doing requests in different controllers and now duplicated methods are in all those controllers. What is the best way to abstract that code (requests) in a single class, so I can easily re-use the code, so I can keep the controllers more simple.
Please save me from what I feel to be a redundant and repetitive coding sequence.
I have tried to make a singleton class, but each view controller requires different request connect points, and most view controllers require specific actions to be called when the succeeded method is called and Im not sure how to handle it all.
Here is what my code template currently looks like in the Objective-c program:
//*1) Somewhere at the top of my .m file I have this*
//These are the suffixes to the URL path that I connect to at my server,
//depending on the action required
NSString *const RequestCreateCustomer = #"Create/Customer";
NSString *const RequestUpdateCustomer = #"Update/Customer";
NSString *const RequestDeleteCustomer = #"Delete/Customer";
//*2) Then I have my connection invocation code*
//Method invocation, all of them look something like this
-navigationButton{
...
[self retrieveWithRequestStringType:RequestUpdateCustomer];
}
-(void)retrieveWithRequestStringType:(NSString*)typeOfRequest{
NSLog(#"Retrieve %# method called", typeOfRequest);
NSString *urlString = [NSString stringWithFormat:#"%#/Secure/CB/%#", #"http://www.defaultStapleURLToMyServer.com/CB", typeOfRequest];
NSString *encodedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:encodedUrlString];
serverRequest = nil;
serverRequest = [ASIFormDataRequest requestWithURL:url];
[serverRequest addRequestHeader:#"Content-Type" value:#"application/json"];
[serverRequest addRequestHeader:#"Request-Method" value:#"POST"];
//Normally at this point depending on the request type, I prepare some data that needs to be sent along with the request
NSMutableDictionary *completeDataArray = [[NSMutableDictionary alloc] init];
if([typeOfRequest isEqualToString:RequestCreateCustomer]){
[serverRequest setUserInfo:[NSDictionary dictionaryWithObject:RequestCreateCustomer forKey:#"RequestType"]];
if( ! [self validateAndPrepareAllData:&completeDataArray]){
return;
}
}
else if([typeOfRequest isEqualToString:RequestUpdateCustomer]){
[serverRequest setUserInfo:[NSDictionary dictionaryWithObject:RequestUpdateCustomer forKey:#"RequestType"]];
if( ! [self validateAndPrepareAllData:&completeDataArray]){
return;
}
}
else if([typeOfRequest isEqualToString:RequestDeleteCustomer]){
[serverRequest setUserInfo:[NSDictionary dictionaryWithObject:RequestDeleteCustomer forKey:#"RequestType"]];
if( ! [self validateAndPrepareCustomerIdData:&completeDataArray]){
return;
}
}
NSString *jsonString = [completeDataArray JSONRepresentation];
[serverRequest appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[serverRequest setDelegate:self];
[serverRequest setDidFinishSelector:#selector(requestSucceeded:)];
[serverRequest setDidFailSelector:#selector(requestFailed:)];
[serverRequest startAsynchronous];
}
//*3) And heres the connection did succeed, and connection did fail methods*
-(void)requestSucceeded:(ASIHTTPRequest*)request{
NSInteger statusCode = [[[request responseHeaders] objectForKey:#"StatusCode"] intValue];
NSLog(#"StatusCode: %#", [[request responseHeaders] objectForKey:#"StatusCode"]);
NSString *myString = [[NSString alloc] initWithData:[request responseData] encoding:NSUTF8StringEncoding];
NSDictionary *JSONDictionary = [myString JSONValue];
switch (statusCode) {
case 400:
case 401:
{
NSLog(#"display error message");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[[request.responseString JSONValue] objectForKey:#"Message"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
break;
}
case 200:
NSLog(#"status code = 200 so successful");
//Created customer request succeeded
if([[[request userInfo] objectForKey:#"RequestType"] isEqualToString:RequestCreateCustomer]){
[self.delegate addedCustomerVCWithCustomer:[[CustomerDataModel alloc] initWithJSONData:[JSONDictionary objectForKey:#"CustomerObject"]]];
[self cancelModalView];
}
//Edit customer request succeeded
else if([[[request userInfo] objectForKey:#"RequestType"] isEqualToString:RequestUpdateCustomer]){
[self.delegate editedCustomerVCWithCustomer:[[CustomerDataModel alloc] initWithJSONData:[JSONDictionary objectForKey:#"CustomerObject"]]];
[self cancelModalView];
}
//Delete customer request succeeded
else if([[[request userInfo] objectForKey:#"RequestType"] isEqualToString:RequestDeleteCustomer]){
[self.delegate deletedCustomer:customer];
[self cancelModalView];
}
break;
default:
[SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:#"went to none: %d or %#", (int)statusCode, [[request responseHeaders] objectForKey:#"StatusCode"]]];
NSLog(#"went to none: %d or %#", (int)statusCode, [[request responseHeaders] objectForKey:#"StatusCode"]);
break;
}
[SVProgressHUD dismiss];
}
-(void)requestFailed:(ASIHTTPRequest*)request{
if([[[request userInfo] objectForKey:#"RquestType"] isEqualToString:RequestCreateCustomer]){
NSLog(#"retrieving states failed so trying again");
[self addCustomerRequest];
}
else if(){
//... you get the point
}
}
Can someone help out with an alternative solution?
create a new class that has blocks/delegate (but prefers block) on it.. let's say Request.h and Request.m.. and make a public method with a block parameter.. example
this should be public methods
typedef void(^CompletionBlock)(id results);
typedef void(^ErrorBlock)(NSError *error);
- (void)setCompetionBlock:(CompletionBlock)block; and
- (void)setErrorBlock:(ErrorBlock)error;
and make a variable name.. this should be private variables
CompletionBlock completionBlock;
ErrorBlock errorBlock;
and declare this methods in your .m
- (void)setCompletionBlock:(CompletionBlock)aCompletionBlock {
completionBlock = [aCompletionBlock copy];
}
- (void)setErrorBlock:(ErrorBlock)aError {
errorBlock = [aError copy];
}
- (void)reportSuccess:(id)results {
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(results);
});
}
}
- (void)reportFailure:(NSError *)error {
if (errorBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
errorBlock(error);
});
}
}
and call [self reportSuccess:jsonSuccess]; under your success methods, in your code it is -(void)requestSucceeded:(ASIHTTPRequest*)request{ and [self reportFailure:NSerror*] under -(void)requestFailed:(ASIHTTPRequest*)request
and to call this class
Request *req = [Request alloc]init];
[req retrieveWithRequestStringType:#"sample"];
[req setCompletion:^(id result){
}];
[req setErrorBlock:(NSError *error) {
}];

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
}
}

We were unable to find the authorization token on LinkedIn login in iOS sdk

I have my iOS app working fine till now but today I faced the problem "We were unable to find the authorization token." which is happening sometimes(most of the time it is working fine).Strangely when I tried to login my LinkedIn account on my desktop I faced the same issue for the first time.I have been implementing same code in many apps but all were working fine.But today I got this issue in my new app.
Code Snippet:
Request Token:
- (void)requestTokenFromProvider
{
LOAMutableURLRequest *request =
[[[LOAMutableURLRequest alloc] initWithURL:requestTokenURL
consumer:self.consumer
token:nil
callback:linkedInCallbackURL
signatureProvider:nil] autorelease];
[request setHTTPMethod:#"POST"];
LOARequestParameter *nameParam = [[LOARequestParameter alloc] initWithName:#"scope" value:#"r_fullprofile+w_messages+r_network+r_emailaddress+rw_nus"];
NSArray *params = [NSArray arrayWithObjects:nameParam, nil];
[request setParameters:params];
LOARequestParameter * scopeParameter=[LOARequestParameter requestParameter:#"scope" value:#"r_fullprofile w_messages r_network r_emailaddress rw_nus"];
[request setParameters:[NSArray arrayWithObject:scopeParameter]];
LOADataFetcher *fetcher = [[[LOADataFetcher alloc] init] autorelease];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(requestTokenResult:didFinish:)
didFailSelector:#selector(requestTokenResult:didFail:)];
}
- (void)requestTokenResult:(LOAServiceTicket *)ticket didFinish:(NSData *)data
{
if (ticket.didSucceed == NO)
return;
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
self.requestToken = [[LOAToken alloc] initWithHTTPResponseBody:responseBody];
[responseBody release];
[self allowUserToLogin];
}
- (void)requestTokenResult:(LOAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
Linkedin Login Page And Access Token:
- (void)allowUserToLogin
{
NSString *userLoginURLWithToken = [NSString stringWithFormat:#"%#?oauth_token=%#",
userLoginURLString, self.requestToken.key];
userLoginURL = [NSURL URLWithString:userLoginURLWithToken];
NSURLRequest *request = [NSMutableURLRequest requestWithURL: userLoginURL];
[webView loadRequest:request];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = request.URL;
NSString *urlString = url.absoluteString;
addressBar.text = urlString;
[activityIndicator startAnimating];
BOOL requestForCallbackURL = ([urlString rangeOfString:linkedInCallbackURL].location != NSNotFound);
if ( requestForCallbackURL )
{
BOOL userAllowedAccess = ([urlString rangeOfString:#"user_refused"].location == NSNotFound);
if ( userAllowedAccess )
{
[self.requestToken setVerifierWithUrl:url];
[self accessTokenFromProvider];
}
else
{
// User refused to allow our app access
// Notify parent and close this view
// [[NSNotificationCenter defaultCenter]
// postNotificationName:#"loginViewDidFinish"
// object:self
// userInfo:nil];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"LinkedInCancelled"];
[[ImpActivityAgent defaultAgent] makeBusy:NO];
[self dismissViewControllerAnimated:NO completion:nil];
}
}
else
{
// Case (a) or (b), so ignore it
}
return YES;
}
- (void)accessTokenFromProvider
{
[[NSUserDefaults standardUserDefaults] setObject:self.consumer forKey:#"LinkedinConsumer"];
LOAMutableURLRequest *request =
[[[LOAMutableURLRequest alloc] initWithURL:accessTokenURL
consumer:self.consumer
token:self.requestToken
callback:nil
signatureProvider:nil] autorelease];
[request setHTTPMethod:#"POST"];
LOADataFetcher *fetcher = [[[LOADataFetcher alloc] init] autorelease];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(accessTokenResult:didFinish:)
didFailSelector:#selector(accessTokenResult:didFail:)];
}
- (void)accessTokenResult:(LOAServiceTicket *)ticket didFinish:(NSData *)data
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
[[NSUserDefaults standardUserDefaults] setObject:responseBody forKey:#"AccessTokenresponseBody"];
BOOL problem = ([responseBody rangeOfString:#"oauth_problem"].location != NSNotFound);
if ( problem )
{
NSLog(#"%#",responseBody);
}
else
{
self.accessToken = [[LOAToken alloc] initWithHTTPResponseBody:responseBody];
[[NSUserDefaults standardUserDefaults] setObject:responseBody forKey:#"accessToken"];//save here
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:#"TokenRefreshDate"];//save here
[[NSUserDefaults standardUserDefaults] synchronize];
}
// Notify parent and close this view
[[NSNotificationCenter defaultCenter]
postNotificationName:#"loginViewDidFinish"
object:self];
[self dismissViewControllerAnimated:NO completion:nil];
[responseBody release];
}
Request Urls:
- (void)initLinkedInApi
{
apikey = #"vwu3pmtjaxyz";
secretkey = #"XkPxP1DNANMg0Dzq";
self.consumer = [[LOAConsumer alloc] initWithKey:apikey
secret:secretkey
realm:#"http://api.linkedin.com/"];
requestTokenURLString = #"https://api.linkedin.com/uas/oauth/requestToken";
accessTokenURLString = #"https://api.linkedin.com/uas/oauth/accessToken";
userLoginURLString = #"https://www.linkedin.com/uas/oauth/authorize";
linkedInCallbackURL = #"hdlinked://linkedin/oauth";
requestTokenURL = [[NSURL URLWithString:requestTokenURLString] retain];
accessTokenURL = [[NSURL URLWithString:accessTokenURLString] retain];
userLoginURL = [[NSURL URLWithString:userLoginURLString] retain];
}
Can somebody please tell me what can be reason behind it?
I have posted this question to LinkedIn forum too where I got the response that there was some issue from their side as other other developers have also reported them the issue.
As per Kamyar Mohager LinkedIn Employee
Is this happening when you're authorizing a new user or are you trying to make calls with existing access tokens? Based on that error message, my assumption is that you're taking users through the auth flow and seeing the error message upon redirect to LinkedIn.com. Please confirm. We're looking into this issue as other developers have reported it.
Then only the following comment he has assured that the problem is resolved.
He Said:
Our team has resolved the "We were unable to find the authorization token" issue when redirecting users through the auth flow. Please let me know if any of you continue to experience this issue.

uploadedFile not called

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

Resources