0

I need some help. I am calling the login function from another class,

// Login on server
- (BOOL) login:(NSString*) username password:(NSString*)password
{
  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:subscribedAppsURL]];
  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  [connectionDict setObject:connection forKey:@"login"];
  [connection release];
  return true;
}

// delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
  NSLog(@"Finished Loading");

    if (connection == [connectionDict objectForKey:@"login"]) {
    [connection release];
    //@TODO Here I want to function login to return true.
  }

}

At the end of connectionDidFinishLoading I want to return the TRUE/ FALSE value in the function login. Does anyone have some suggestions? Thanks!

4

1 に答える 1

2

You can send your request synchronously like this:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:subscribedAppsURL]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if (error != nil)
{
    NSString *stringResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Reponse:%@", response);

    //Handle the response, possible just return true here:
}
else
{
    NSLog(@"Error:%@", error.localizedDescription);
}

With the intent of using delegates:

//In Header
@protocol LoginCompletionDelegate
-(void) didCompleteAndIsLoggedIn:(BOOL) loggedIn;
@end

@property (nonatomic, assign) id<LoginCompletionDelegate> delegate;


//In implementation
- (BOOL) loginWithDelegate:(id<LoginCompletionDelegate>)target username:(NSString*) username password:(NSString*)password
{
   delegate = target;
  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:subscribedAppsURL]];
  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  [connectionDict setObject:connection forKey:@"login"];
  [connection release];
  return true;
}

// delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
  NSLog(@"Finished Loading");

    if (connection == [connectionDict objectForKey:@"login"]) {
    [connection release];
    //@TODO Here I want to function login to return true.
    [delegate didCompleteAndIsLoggedIn:YES];
  }

}

//There is another method that looks like this. I might have the signature a bit wrong
-(void) connection:(NSURLConnection*) connection didFailWithError:(NSError*) error
{
    [delegate didCompleteAndIsLoggedIn:NO];
}
于 2012-06-13T12:17:06.373 に答える