iOS - "Upload progress view" like the new facebook app - ios

I would like to have an "Upload-progress-view", in my app. Just like the one the new Facebook app has. The "Upload view" is only visible if an upload-progress is active.
The UIView shoud be visible on every UIViewController in my app.
Can I insert the "Upload-progress-view" in my AppDelegate?
I'am using AFNetworking.
/ Morten
Screenshot:
As you can see it is a simpel UIView with a UIProgressView in it. My problem is how do I show this progress-view on every views (different UIViewControllers)?

This progressBar can do the same behaviour.

Are you using ASIHttpRequest to do the upload?
If yes take a look at Cocoa File Upload with Progress Bar
EDITED:
Ok, so use this
NSURL *url = [NSURL URLWithString:#"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:#"avatar" fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];
from GitHub AFNetworking - File Upload with Progress Callback

Related

AFNetworking and downloading images

I want to know is there way to download images with my code one by one ? Now async
NSString *urlString = link;
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
completion(operation, responseObject, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[RequestAPI sharedInstance].downloadsCount -= 1;
DDLogError(#"FAIL download image: %#",error);
}];
[requestOperation start];
Try this solution
Create a NSObject class for downloading the images. Lets call this DownloadImages. The class has an array of images to be downloaded arrayOfImagesURL.
Create a delegate for the class DownloadImages to make a call back when you finish downloading an image. View how to this in detail here.
Implement AFNetworking as you like, you can also accomplish this by using the iOS 7 API NSURLSession. So in the completion block of your download task, you need to do 2 things:
Continue downloading the next URL in arrayOfImagesURL.
Do a call back with the delegate to the parent controller for processing.
Tell me if there's something need to be more clarify.

AFNetworking 2.0 download multiple images with completion

I'm trying to figure out a way to download multiple images with AFNewtorking 2.0. I've read a lot of posts here in SO, but can't find the answer I'm looking for, hope you guys can help me.
The problem is that I want to know when all of the downloads finished and if all images where downloaded.
So I have an array with image URL's ant trying to do something like this.
for(NSString *photoUrlString in self.photos){
NSURL *url = [NSURL URLWithString:photoUrlString];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:url]];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Image error: %#", error);
}];
[requestOperation start];
}
I've found some answers with putting these requests into a queue and setting max concurrent operations to 1. But don't know how that works really.
Any help is appreciated, thanks in advance!
for(Photo *photo in array){
//form the path where you want to save your downloaded image to
NSString *constPath = [photo imageFullPath];
//url of your photo
NSURL *url = [NSURL URLWithString:photo.serverPath];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:url]];
op.responseSerializer = [AFImageResponseSerializer serializer];
op.outputStream = [NSOutputStream outputStreamToFileAtPath:constPath append:NO];
op.queuePriority = NSOperationQueuePriorityLow;
[op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead){
}];
op.completionBlock = ^{
//do whatever you want with the downloaded photo, it is stored in the path you create in constPath
};
[requestArray addObject:op];
}
NSArray *batches = [AFURLConnectionOperation batchOfRequestOperations:requestArray progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
} completionBlock:^(NSArray *operations) {
//after all operations are completed this block is called
if (successBlock)
successBlock();
}];
[[NSOperationQueue mainQueue] addOperations:batches waitUntilFinished:NO];
Try this:
// _group, _queue are iVar variable
dispatch_group_t *_group = dispatch_group_create();
dispatch_queue_t *_queue = dispatch_queue_create("com.company.myqueue2", NULL);
// all files download
for(int i = 0 ; i < numberOfFileDownloads; i++){
dispatch_group_async(_group, _queue, ^{
// here is background thread;
// download file
});
}
// all files are download successfully, this method is called
dispatch_group_notify(_group, _queue, ^{
}
Check out +[AFURLConnectionOperation batchOfRequestOperations:progressBlock:completionBlock:]
Although it's not documented, implementation is self-explanatory. Also it allows you to monitor the progress.
You will need to have an array of HTTP operations prior to using this method (this is if you decided to stick to NSURLConnection-based implementation of AFNetworking).

Bulk Video Upload with AFNetworking

I am attempting to get AFNetworking (1.x) to batch upload some long videos to my server, however when I use the standard functions the application's memory spikes to 400MB and then quits.
NSMutableArray *requests = [[NSMutableArray alloc] init];
NSMutableURLRequest *request = [[MyServerClient sharedClient] multipartFormRequestWithMethod:#"POST" path:URL parameters:#{ #"json": jsonString } constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:mediaData name:idString fileName:fileName mimeType:mimeType];
}];
[request setTimeoutInterval:10800];
[requests addObject:operation];
[[MYServerClient sharedClient] enqueueBatchOfHTTPRequestOperationsWithRequests:requests progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) {
NSLog(#"Number - %d %d", numberOfCompletedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
NSLog(#"Completion block");
}];
The MyServerClient is a pretty standard subclass of AFHTTPClient:
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
[self.operationQueue setMaxConcurrentOperationCount:1];
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
return self;
}
I'm guessing the memory crash might have something to do with the application failing to throttle the amount of concurrent operations, but in light of setting setMaxConcurrentOperationCount, I'm not sure. Does anyone have any ideas why this would be happening?
EDIT: My guess is that the crash is due to the app attempting to load the media into memory prior to attaching it to the multipart request. Is there some way to stream the upload from disk within this POST usage scenario?
For anyone struggling with the same issue, the following appears to fix my crash:
NSMutableURLRequest *request = [[MyServerClient sharedClient] multipartFormRequestWithMethod:#"POST" path:URL parameters:#{ #"json": jsonString } constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:mediaURL name:idString error:nil];
}];

Sending multiple Images to Web server

I am working in an app, where i need to send 3 images to a Web Server. I don't know the perfect method that works fast and efficient.
I have 3 UIImageView that capture image data from camera or photo album. Below,I am using AFNetworking to send 1 image to Web Server.
NSString *imgPath = [[NSBundle mainBundle]pathForResource:#"Default" ofType:#"png"];
NSData *imgData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:imgPath]);
NSData *imagVIewData = UIImageJPEGRepresentation(imageView1.image,90);
if (imagVIewData) {
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://myurl.com/xxx.php]];
NSMutableURLRequest *myRequest = [client multipartFormRequestWithMethod:#"POST" path:Nil parameters:Nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imagVIewData name:#"file_upload" fileName:#"123.jpg" mimeType:#"images/jpeg"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:myRequest];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes",totalBytesWritten,totalBytesExpectedToWrite);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"upload complete");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",operation.responseString);
}];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:operation];
}
}
i need someone advice to send 3 different images from 3 UIImageViews. Is it possible with this program or do i need to work through different methods?
any idea?
The majority of the code you have can actually be kept. Why not try putting all the JPEG representations of the images into an array
NSArray *myArrayOfImages = #[Image1,Image2,Image3]
NSArray *myArrayOfNames = #[strings..]
NSArray *myArrayOfFileNames = #[strings..]
Then within the constructing body with block parameter put something like this..
for(int i=0; i < myArrayOfImages.length; i++){
NSData *temp = [myArrayOfImages objectAtIndex:i];
NSString *tempFile = [myArrayOfNames objectAtIndex:i]
NSString *tempFile = [myArrayOfFileNames objectAtIndex:i]
[formData appendPartWithFileData:temp name:tempName fileName:tempFile mimeType:#"images/jpeg"];
}
you could also use a dictionary or whatever data structure you want, point is you just loop over and append within the constructing block.

iOS: How to use operation queues to download large amount of data?

I am developing an iOS application in which I have to download large data like images and videos locally on device. The data can be in GB's and there can be thousands of files to download. So, whats the best way to tackle this situation. Because it can have many failures like request time out etc.
Also I have to updated core data that if the file has been successfully downloaded or not.
Any best and simple way would be appreciated.
Try taking a look at AFNetworking framework, handles almost everything for you and probably faster then you could implement.
Also do the downloading on a background thread using GCD. I've had decent results downloading 50Mb files.
You can use AFNetworking for that. it is a best API for dealing with web services now a days .you can download Latest AFNetworking API for iOS from github and.
you can use
- (void)uploadImageAtUrl:(NSURL*)url
{
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:#"yourImg.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:#"yourImg" fileName:#"yourImg.jpg" mimeType:#"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
//Check progress
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
}

Resources