2012-10-08 79 views
1

我使用NSURLConnection通過https進行身份驗證,工作正常,但使用NSData下載文件時,我無法訪問內容。如何通過經過驗證的網址下載文件?如何通過iOS中的認證網址下載文件?

這裏就是我試圖讀取下載的文件的內容(這裏不包括認證碼),服務器說,「用戶未授權」:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 

NSFileManager *fileManager = [NSFileManager defaultManager]; 

      // Attempt to open the file and write the downloaded data to it 
      if (![fileManager fileExistsAtPath:documentsDirectory2]) { //download path 
       [fileManager createFileAtPath:documentsDirectory2 contents:nil attributes:nil]; 
      } 
      // Append data to end of file 
      NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:documentsDirectory2]; 
      [fileHandle seekToEndOfFile]; 
      [fileHandle writeData:data]; 
      [fileHandle closeFile]; 



      //data.txt exists, read me its content 
      NSArray *paths8 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString *documentsDirectory8 = [paths8 objectAtIndex:0]; 
      NSString *filePath8 = [documentsDirectory8 stringByAppendingPathComponent:@"data.txt"]; 
      NSString *content8 = [NSString stringWithContentsOfFile:filePath8 encoding:NSUTF8StringEncoding error:NULL]; 
      NSLog(@"WHATS INSIDE DATA.TXT? =%@", content8); 

      [self.responseData appendData:data]; 
      } 
+0

可以顯示一些代碼 –

+0

肯定的是,它已經更新。 – sunny

+0

如果你的錯誤是'user not authorized',那麼你可能應該包含你的驗證代碼.... – lnafziger

回答

1

您需要使用NSURLCredential來在實現NSURLConnectionDelegate時進行身份驗證。

繼承人例如:

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
{ 
    return YES; 
} 

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    NSURLCredential *credential = [NSURLCredential credentialWithUser:username 
                  password:passwd] 
                  persistence:NSURLCredentialPersistenceForSession]; 

    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 
} 
+0

Alexandresoli,我更新了這個問題,並且爲了清晰起見,在上面的例子中省略了nsurlcredential代碼。身份驗證在閱讀json文件時工作正常,但如果我想下載不同的文件類型(比如mp4),我無法訪問它。 – sunny

+0

嘗試檢查服務器中的權限,如果您可以從瀏覽器訪問該文件,代碼應該可以正常工作。 – alexandresoli

+0

問題是,該文件無法通過瀏覽器訪問,因爲它需要用戶名/密碼進行身份驗證。 – sunny