我正在执行一个简单的请求,以下载PDF文件,然后将其写入文件路径。
一些PDF被定向到故障块。
我得到的错误代码为200,错误描述为“传输关闭,剩余2231939个字节可供读取”。
下面是代码片段。
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:nil
timeoutInterval:120];
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (operation.response.statusCode != 200) {
NSLog(@"Error code(S): %d",[operation.response statusCode]);
}else{
NSData *data = [[NSData alloc] initWithData:responseObject];
[data writeToFile:filePath atomically:YES];
NSLog(@"successful download to %@", filePath);
[data release];
}
[self fetchComplete:operation type:type];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error code: %d",[operation.response statusCode]);
NSLog(@"error discreption: %@",[error localizedDescription]);
[self fetchFailed:operation];
}];
最佳答案
请尝试这个例子。希望有帮助!
//步骤1:创建具有下载文件完整路径的NSURL
//例如,请尝试:NSString * fileUrl = @“https://pbs.twimg.com/profile_images/2331579964/jrqzn4q29vwy4mors75s_400x400.png”;
//并使用我们的URL创建NSURLRequest对象
NSURL *URL = [NSURL URLWithString:fileUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//步骤2:保存下载文件的名称
//例如,我们的fileName字符串等于'jrqzn4q29vwy4mors75s_400x400.png'
NSString *fileName = [URL lastPathComponent];
//步骤3:使用我们的请求创建AFHTTPRequestOperation对象
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//步骤4:设置服务器答复和请求错误的处理
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// here we must create NSData object with received data...
NSData *data = [[NSData alloc] initWithData:responseObject];
// ... and save this object as file
// Here 'pathToFile' must be path to directory 'Documents' on your device + filename, of course
[data writeToFile:pathToFile atomically:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"file downloading error : %@", [error localizedDescription]);
}];
//步骤5:开始异步下载
[downloadRequest start];
关于ios - 用AFNetworking 2.0下载PDF,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28673918/