I have the following scenario: in my DocumentsDirectory there are user-created pdf-files. Now I want to upload them all to a webserver. When successfully done, i want to remove the file from the device.
My first problem is, that I do not know, when the upload is successful for a specific file. Additionally I get errors on some files.
At first some code:
-(void)uploadPDFs
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:docsDir error:nil];
for (NSString *filename in contents) {
if([filename.pathExtension isEqualToString:@"pdf"])
{
NSURL *docsDirURL = [NSURL fileURLWithPath:[docsDir stringByAppendingPathComponent:filename]];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setTimeoutIntervalForResource:10];
NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@/api/putPdf?name=%@&folder=", [defaults objectForKey:@"serverAdresse"], filename]];
NSData *pdfData = [NSData dataWithContentsOfFile:docsDirURL.path];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:@"application/pdf" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[pdfData length]] forHTTPHeaderField:@"Content-Length"];
[request setTimeoutInterval:60];
// UploadTask is a NSURLSessionUploadTask
self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromData:pdfData];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[self.uploadTask resume];
}
}
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
});
if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"NO ERROR");
// CAN I GET HERE THE UPLOADED FILENAME?
});
} else {
NSLog(@"ERROR: %@", error);
}
}
The error I get especially when there are many uploads:
(-[ViewController URLSession:task:didCompleteWithError:]) (ViewController.m:4025) ERROR: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x7fa3957028f0 {NSErrorFailingURLKey=http://192.168.100.150/api/putPdf?name=2015-03-26_AN_14.pdf&folder=, NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=http://192.168.100.150/api/putPdf?name=2015-03-26_AN_14.pdf&folder=}
Use the taskDescription
property of an NSURLSessionUploadTask. ` For example;
task.taskDescription = filePath;
`
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다