2013-12-20 76 views
2

我已經編寫了一個提供某些數據的REST服務。它是密碼保護。帶有身份驗證的NSURLSession的簡單示例

我想寫一個後臺進程,將抓取數據並將其填充到我在應用程序中的sqlLite數據庫中。

- (void) callWebService { 
    dispatch_sync(kBgQueue, ^{ 
     NSData* data = [NSData dataWithContentsOfURL: 
         scoularDirectoryURL]; 
     [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; 
    }); 
} 

這工作得很好,但我不認爲我可以添加認證到:

我最初使用這樣做無需認證。如果我能我會使用它。

我在找的是使用用戶/密碼認證的NSURLSession的一個很好的簡單的解釋。

回答

7

我認爲你的問題含糊不清,這就是說,這裏有一個解決方案,從here

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)( NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler 
{ 
    if (_sessionFailureCount == 0) { 
     NSURLCredential *cred = [NSURLCredential credentialWithUser:self.userName password:self.password persistence:NSURLCredentialPersistenceNone];   
    completionHandler(NSURLSessionAuthChallengeUseCredential, cred); 
    } else { 
     completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); 
    } 
    _sessionFailureCount++; 
} 

我強烈建議您閱讀和重新閱讀本的Apple docs

+0

謝謝。將會採取建議。 –

+0

只需提一下,'NSURLAuthenticationChallenge'包含'previousFailureCount'。所以不需要單獨維護它,除非你有一些定製的計算失敗的方法。 – execv

0

對我來說,下面的代碼工作:

NSString *[email protected]"user:"; 
NSString *[email protected]"password"; 
NSString *authStr= [userName stringByAppendingString:userPassword]; 
NSString *[email protected]"http://000.00.0.0:0000/service.json"; 

NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]]; 
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; 
[request setValue:authValue forHTTPHeaderField:@"Authorization"]; 

[NSURLConnection sendAsynchronousRequest:request 
            queue:[NSOperationQueue mainQueue] 

         completionHandler:^(NSURLResponse *response, 
              NSData *data, NSError *connectionError) 

NSDictionary *theDictionary = [NSJSONSerialization JSONObjectWithData:data 
                    options:0 
                    error:NULL]; 

NSDictionary *host = [theDictionary objectForKey : @"host"]; 
     // json nested 
      self.label.text = [host objectForKey:@"key1"]; 
      self.label.text = [host objectForKey:@"key2"]; 

問候