ios - 如何在 iOS 中通过经过身份验证的 url 下载文件?

标签 ios authentication download nsurlconnection nsdata

我正在使用 NSURLConnection 通过 https 进行身份验证,这工作正常,但是当使用 NSData 下载文件时,我无法访问内容。如何通过经过身份验证的 URL 下载文件?

这是我尝试读取下载文件内容的地方(此处未包含验证码),服务器显示“用户未授权”:

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

最佳答案

在实现 NSURLConnectionDelegate 时需要使用 NSURLCredential 进行身份验证。

举个例子:

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

关于ios - 如何在 iOS 中通过经过身份验证的 url 下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774150/

相关文章:

http - AppleScript 从 HTTP 服务器下载文件,改变 URL?

ios - UITableView didSelectRowAt 无法继续到下一个 View Controller

c# - 使用 StreamWriter 的文件中的 NULL 符号

javascript - 检测网络用户当前是否已登录 Google?

MySQL 纯文本哈希密码

java - 为什么使用线程不能加速我的程序? java

bash - 使用 url 重定向下载文件

ios - 从白色 iOS 7/Xcode 5 更改状态栏文本颜色

ios - Swift 泛型中的文字

javascript - 编辑路径身份验证页面时出现问题