使用同步方式iOS连接到安全服务器

时间:2015-03-21 16:08:27

标签: ios asynchronous server

我想知道是否有一种方法可以通过同步方式连接到安全的Web服务(Web服务器请求用户名和密码来连接和返回数据)以及如何在我的代码中传递这两个参数,我使用过这段代码:

-(void)performRequest{
NSURL * url =[[NSURL alloc] initWithString:@"http://firstluxe.com/api/tags/?display=[id,name]&output_format=JSON"];
NSURLRequest * request = [[NSURLRequest alloc] initWithURL:url];

NSURLConnection * connection =[[NSURLConnection alloc]initWithRequest:request
delegate:self];}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if ([challenge previousFailureCount] == 0)
{
    NSURLCredential * cred = [NSURLCredential credentialWithUser: @"userName"
                                                        password: @"Password"
                                                     persistence: NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
}
else
{
    //You don't have authentication
}
}
-(BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
{
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {
//handle errors
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
 html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
jsonFromAFNetworking = html;
NSLog(@" html is %@ ",html);
}

它正确地从服务器返回值,但是当我这样做时:

- (void)viewDidLoad {
[super viewDidLoad];
[self performRequest];
NSLog(@" jsonFromAFNetworking %@" , jsonFromAFNetworking);
}

我得到空值,我知道它是因为它是异步操作,但我需要使用新值而我不知道该怎么做,我怎么能告诉代码等到执行[self performRequest]或如何通过其他方式连接到此服务器?

0 个答案:

没有答案