Couldn't download from url in my app with AFNetwotking - ios

Im noob in AFNetworking and I learning it now. I want download file from url and save in my app (Document Folder) but it dosen't work.I have one button that when click it start download.
this is my code for download file :
- (IBAction)downloads:(id)sender
{
NSLog(#"start downloads");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.100/mamal/filemanager.php"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:[path stringByAppendingPathComponent:#"filemanager.php"] append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
in this code when click on button take me this massage = 'start downloads' but dont show me 'Successfully downloaded file to %#' why?? my code not complete???

You didn't start the operation. Use the following line to start the operation :
[operation start];

Related

Upload video chuck downloaded from one server to another server using AFNetworking

I am making an app that will transmit data from glasses to the server for broadcasting.
Til now i am able to download data from glasses to my iPhone document directory.
now i want to upload that downloaded data to my server so that we can broadcast that data to our users.
My iPhone and glasses are connected with each other with the help of WiFi, and i am trying to upload downloaded data via cellular network.
So basically my concept is that download data from glasses and upload that to server.
I have try to make my iPhone as a server to that my back end team could download data from my iPhone.
I got success in this method but the problem is that for this process the client and server should be on same private ip networks.
so now we have left with only one way that we download TS chucks from glasses and same time upload the TS file to our server for broadcasting.
I am using NFNetworking to download video chucks from glasses "TS File" but not able to upload that chucks to my server.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://xxx.xx.xx.x/abc/trunk/WebServices/app/webroot/xyz"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ;
operation.outputStream = [NSOutputStream outputStreamWithURL:[NSURL URLWithString:#"http://abc.aa.a.a/xyz/trunk/WebServices/app/webroot/img/glasses/test/demo.ts"] append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSLog(#"Successfully downloaded file to %#", path);
// NSLog(#"download finished!");
if(_delegate && [_delegate respondsToSelector:#selector(ZBTM3U8SegmentDownloaderFinishDownload:)])
{
[_delegate ZBTM3U8SegmentDownloaderFinishDownload:self];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// NSLog(#"Error: %#", error);
}];
[operation start];
It goes in success state but data is not uploaded on server
server folder show empty.
- (void)postVideoOnServer {
NSDictionary *requestDict = #{ #"uniqueToken":#"101", #"user_id":#"102",};
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:_tsFileName];
NSData *selectedVideo = [NSData dataWithContentsOfFile:path];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation = [manager POST:#"http://xxx.x.x.xx/myi/public_html/WebServices/broad/axy" parameters:requestDict constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
[formData appendPartWithFileData:selectedVideo name:#"file" fileName:#"filename.ts" mimeType:#"video/quicktime"];
} success: ^(AFHTTPRequestOperation *operation, id responseObject)
{
NSInteger statusCode = operation.response.statusCode;
NSLog(#"Status Code ::%d", statusCode);
NSLog(#"Response ::%#", responseObject);
[self handleVideoServiceResponse:responseObject];
}
failure : ^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# %#", operation.responseString, error);
}];
[operation start];
}
it always return request time out error.
Thanks in advance.
Are you sure NSData *selectedVideo is not nil? i doubt you mime type too? Just a suggestion try use MIME: video/MP2T, it should fix your problem.

AFNetworking: download + resume big file?

I'm using AFNetworking to download a big file. Here is my code. It work fine:
- (AFDownloadRequestOperation*)downloadBigFile:(BigFileObject*)bigFile
withCompleteBlock:(AFResultCompleteBlock)completeBlock
errorBlock:(AFResultErrorBlock)errorBlock{
NSString *name = [NSString stringWithFormat:#"%#", bigFile.name];
NSString *link = [NSString stringWithFormat:#"%#", bigFile.link];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:link]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp4", name]];
AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:path shouldResume:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
completeBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
errorBlock(error);
}];
[operation setProgressiveDownloadProgressBlock:^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
float progress = (float)totalBytesReadForFile / totalBytesExpectedToReadForFile;
//block
self.progressBlock(progress, totalBytesReadForFile, totalBytesExpectedToReadForFile);
}];
[operation start];
return operation;
}
A file is being downloaded to local but not finished, take 30% finished for an example. Then stop it. Few day late, I resume it, but that link was not live. So, I request a new link and I wanna download from 30%. How to do it?
My app is target iOS 6+;

Memory pressure issue while downloading multiple files using AFNetworking

In my application i am trying to download thousands of images (each image size with a maximum of 3mb) and 10's of videos (each video size with a maximum of 100mb) and saving it in Documents Directory.
To achieve this i am using AFNetworking
Here my problem is i am getting all the data successfully when i am using a slow wifi (around 4mbps), but the same downloading if i am doing under a wifi with a speed of 100mbps the application is getting memory warning while downloading images and memory pressure issue while downloading videos and then application is crashing.
-(void) AddVideoIntoDocument :(NSString *)name :(NSString *)urlAddress{
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlAddress]];
[theRequest setTimeoutInterval:1000.0];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:name];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
//NSLog(#"Download = %f", (float)totalBytesRead / totalBytesExpectedToRead);
}];
[operation start];
}
-(void)downloadRequestedImage : (NSString *)imageURL :(NSInteger) type :(NSString *)imgName{
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:imageURL]];
[theRequest setTimeoutInterval:10000.0];
AFHTTPRequestOperation *posterOperation = [[AFHTTPRequestOperation alloc] initWithRequest:theRequest];
posterOperation.responseSerializer = [AFImageResponseSerializer serializer];
[posterOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(#"Response: %#", responseObject);
UIImage *secImg = responseObject;
if(type == 1) { // Delete the image from DB
[self removeImage:imgName];
}
[self AddImageIntoDocument:secImg :imgName];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Image request failed with error: %#", error);
}];
[posterOperation start];
}
The above code i am looping according to the number of videos and images that i have to download
What is the reason behind that behaviour
I even have screen shots of memory allocation for both the scenarios
Please Help
Adding code for saving the downloaded images also
-(void)AddImageIntoDocument :(UIImage *)img :(NSString *)str{
if(img) {
NSData *pngData = UIImageJPEGRepresentation(img, 0.4);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePathName =[[paths objectAtIndex:0]stringByAppendingPathComponent:str];
[pngData writeToFile:filePathName atomically:YES];
}
else {
NSLog(#"Network Error while downloading the image!!! Please try again.");
}
}
The reason for this behavior is that you're loading your large files into memory (and presumably it's happening quickly enough that you app isn't having a chance to respond to memory pressure notifications).
You can mitigate this by controlling the peak memory usage by not loading these downloads into memory. When download large files, it's often better to stream them directly to persistent storage. To do this with AFNetworking, you can set the outputStream of the AFURLConnectionOperation, and it should stream the contents directly to that file, e.g.
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentsPath stringByAppendingPathComponent:[url lastPathComponent]]; // use whatever path is appropriate for your app
operation.outputStream = [[NSOutputStream alloc] initToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"successful");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failure: %#", error);
}];
[self.downloadQueue addOperation:operation];
BTW, you'll notice that I'm not just calling start on these requests. Personally, I always add them to a queue for which I've specified the maximum number of concurrent operations:
self.downloadQueue = [[NSOperationQueue alloc] init];
self.downloadQueue.maxConcurrentOperationCount = 4;
self.downloadQueue.name = #"com.domain.app.downloadQueue";
I think this is less critical regarding memory usage than the streaming of the results directly to a outputStream using persistent storage, but I find this is another mechanism for managing system resources when initiating many concurrent requests.
You can start using NSURLSession's downloadTask.
I think this will resolve your issue.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://someSite.com/somefile.zip"]];
[[NSURLSession sharedSession] downloadTaskWithRequest:request
completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error)
{
// Use location (it's file URL in your system)
}];

AFNetworking not supporting DWG files?

I have an In-house Ipad App that opens files that are stored elsewhere on the network through filters, menus, etc.
The Main Formats for the Images are Tiff or PDF, so I convert them to a PDF (if TIFF) using a web-service.
Users are asking to include DWG files and I downloaded a DWG viewer on the Ipad. I would like to use AFNetworking to download the DWG file from the server to the Ipad but it doesn't seem to work.
The same code works great for PDF files:
urlString = [urlString stringByAppendingString:strFile];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:req];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *outputPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:strFile];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:outputPath append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", outputPath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
Thanks,
Shai
From what I understand, AFNetworking can download any file. The problem here was on the Web Server settings, more specifically the Mime settings for .DWG files were missing.

File existence after AFNetworking download

I'm having some issues with finding my file after downloading it with AFNetworking...
The download itself goes fine, but when I check for the existence of the file afterwards, I can't find it... So I'm hoping someone can help me out...
In my code, I download the file, and in the completion block, I check for the existence (this is only done since I'm having issues finding it, it will be removed afterwards)...
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"url to file removed"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"filename removed"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:#"filename removed" append:NO];
//Track the progress
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
if (totalBytesExpectedToRead > 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSString *progress = [NSString stringWithFormat:#"Downloaded %lld of %lld bytes",
totalBytesRead,
totalBytesExpectedToRead];
NSLog(#"%#", progress);
});
}
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"File downloaded to %#", path);
//Check for existence
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath:path])
{
NSLog(#"File found");
} else
{
NSLog(#"File not found");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
[operation start];
Any ideas where it might be going wrong? As the download itself goes fine, the problem must lie with saving the file / the file system in iOS...
Does the directory you're trying to write to exist? If not you may find [NSOutputStream outputStreamToFileAtPath:#"filename removed" append:NO] is returning nil.
Try creating the directory first:
NSFileManager *fm = [NSFileManager defaultManager];
NSString *folder = [#"filename removed" stringByDeletingLastPathComponent];
if (![fm fileExistsAtPath:folder]) {
[fm createDirectoryAtPath:folder
withIntermediateDirectories:YES
attributes:nil
error:nil];
}
I hope that helps.

Resources