iOS:connectionDidFinishLoading

时间:2012-06-13 12:09:42

标签: ios xcode4 ios4

我需要一些帮助。我从另一个类调用login函数,

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

}

在connectionDidFinishLoading结束时,我想在函数登录中返回TRUE / FALSE值。有人有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您可以像这样同步发送请求:

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

目的是使用代表:

//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];
}