Adding a download progress bar using ASIHTTPRequest created on a NSObject class - ios

I have a global NSObject class where I added an ASIHTTPRequest function to update my application. I have set the UIProgressView on a ViewController class. The NSObject class looks like so:
+(void)updateAllWithCategory:(NSMutableArray *)categories{
for(NSMutableArray *item in categories) {
NSString *urlString = [NSString stringWithFormat:#"http://mywebsite.com/%#.xml", item];
NSURL *url = [[NSURL alloc]initWithString:urlString];
__block __weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setShowAccurateProgress:YES];
[request setDownloadProgressDelegate:self];
[request setTimeOutSeconds:20];
[request setCompletionBlock:^{
//download all data and show alert
}];
[request setFailedBlock:^{
//display all errors
}];
[request startAsynchronous];
}}
float bytesReceived = 0;
float totalSize = 0;
float estimate = 0;
+(void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes {
bytesReceived = bytesReceived + (float)bytes;
float dlSize = (float)[request contentLength];
totalSize = totalSize + dlSize;
estimate = (bytesReceived / (totalSize * 1.0f) * 100);
//write estimate in plist with value estTime
}
Then on my view controller I use the said function like so:
-(void)updateChecker {
//get estTime from plist
[GlobalClass updateAllWithCategory:myArray]
progressbar.hidden = NO;
[progressbar setProgress:estTime animated: YES];
progressbar.progress = estTime;
}
updateChecker is called via a NSTimer set on viewDidLoad. Neither setProgress:animated: nor .progress worked. My progress bar does not move even a little. So my question is, how exactly do you implement a progress bar for an ASIHTTPRequest that's called from a global NSObject class?

You need to create a UIProgressView.
UIProgressView *progressView = [UIProgressView alloc] init];
and then replace this
[request setDownloadProgressDelegate:self];
with this
[request setDownloadProgressDelegate:progressView];

Related

uiwebview not working with HTTP or HTTPS urls

i am trying to load a url in uiwebview in xcode and it is loading just fine but problem is that there is ZERO user interaction with it. i can not touch any button on it or can not even scroll it. i have already tried Allow Arbitrary Loads = YES in info.plist but nothing happened here is my code.
[webPage setDelegate:self];
[webPage loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://url.com"]]];
[webPage addSubview:activityIndicatorView];
here is more code from .h:
#interface ViewController : UIViewController<UIWebViewDelegate>{
IBOutlet UIWebView *webPage;
}
#property (retain, nonatomic) IBOutlet UIWebView *webPage;
its s simple uiwbview from interface builder in a simple uiviewcontroller.
and here is my info.plist
I figure out that problem might be here in this part of the code. there is a menu in my uinavigationbar as well which is loading xml menu. wait i will post my code.
- (void) makeMenu{
#try {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0),^{
NSURL *url=[NSURL URLWithString:#"http://url/xml-menu.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
rssOutputData = [[NSMutableArray alloc]init];
xmlParserObject =[[NSXMLParser alloc]initWithData:urlData];
[xmlParserObject setDelegate:self];
[xmlParserObject parse];
}
dispatch_async(dispatch_get_main_queue(), ^{
sideMenu.delegate = self;
NSInteger count;
NSMutableArray *itemsArry = [[NSMutableArray alloc] init];
count = [rssOutputData count];
for (int i = 0; i < count; i++){
BTSimpleMenuItem *item = [[BTSimpleMenuItem alloc]initWithTitle:[[rssOutputData objectAtIndex:i]xmltitle] image:[UIImage imageNamed:#"arrow.png"]
onCompletion:^(BOOL success, BTSimpleMenuItem *item) {
[webPage loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[[rssOutputData objectAtIndex:i]xmllink]]]];
}];
[itemsArry addObject:item];
}
NSArray *itemSarry=[[NSArray alloc] initWithArray:itemsArry];
sideMenu = [[BTSimpleSideMenu alloc]initWithItem:itemSarry addToViewController:self];
});
});
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
}
when i call this method in viewdidload uiwebview stop responding. And if i do not call this part uiwebview works just fine. please help me i need this menu as well.
Try this:
webPage.userInteractionEnabled = YES;

Multi part NSArray Post AFNetworking

I have a large NSArray I am wanting to split into chunks and send to my web server, upon completion of each chunk I then need to update the fields in my SQLite DB that relate to each item in each array chunk.
This is the code I am currently running, where I try to use a call back to receive success or failure then update my local SQLite DB where appropriate.
- (void)postlowData:(NSArray *)lowMArray Callback:(void (^)(NSError *error, BOOL success))callback;
{
// Currently this method is sending the whole lowMArray
// What I want to do is Split lowMArray into a chunkArray (where chunk is 20 of the leading items from lowMArray)
// I would then send chunkArray with the following code, when I receive a response I then want to update local SQLite DB with result and recall this method to start on the next 20 chunks.
// Create Json data from lowMArray
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:lowMArray
options:NSJSONWritingPrettyPrinted
error:nil];
// Construct post request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/lows", _silServerBaseUrl]]];
request = [self applyAuth:request];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
// Send post request
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
// NSLog(#"Response Failed!");
callback(error, NO);
} else {
// NSLog(#"Response Success!");
callback(error, YES);
// On success add itmes from lowChunkArray so that you can adjust sent_Flag later
}
}];
[dataTask resume]; // runs task
}
The issue I am running into is that when I run this code if I am splitting the array into chunks sending the chunk adjusting the main array for the next chunk I don't get a confirmed callback till the very end of all the requests, at which point I have lost track of what success or failure?
Maybe I am going about this the wrong way?
Update
I am now trying to do this using AFHTTPRequestOperation which seems to be working as a batch upload however the
setHTTPBody:jsonData
Never seems to make it to the server.
I used this Batch of Operations example to help me construct this method however as I said above the JSON data never makes it to the server.
- (void)postlowData:(NSArray *)lowMArray;
{
NSLog(#"Syncing Local");
NSArray *chunklow = [[NSArray alloc] init];
NSMutableArray *mutableOperations = [NSMutableArray array];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/lows", _silServerBaseUrl]];
//Test: creating 10 things to send
for (int i = 0; i < 10; i++) {
if ([lowMArray count] > 0) {
if ([lowMArray count] >= 20) {
low = [lowMArray subarrayWithRange:NSMakeRange(0, 20)];
} else if ([lowMArray count] < 20) {
low = [lowMArray subarrayWithRange:NSMakeRange(0, [lowMArray count])];
}
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:low
options:NSJSONWritingPrettyPrinted
error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request = [self applyAuth:request];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[mutableOperations addObject:operation];
}
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog(#"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
NSLog(#"All operations in batch complete");
NSLog(#"Syncing complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];
}
For your problem of splitting insertion of a large array into chunks to be inserted to a DB via network operations, an NSOperationQueue can be created that will allow you to add a separate operation for each chunk of data to be inserted.
The queue can be set to run in a serial manner so that each operation will need to be complete before the next one is started.
Using a queue makes the multiple operations more manageable than having the flow be controlled by callbacks.
In summary, you create a queue and set its maximum concurrent operation count to 1. Then create an NSOperation subclass that performs the necessary steps to insert data into the database. Each chunk of data will correspond to a separate operation that will be added to the queue. Each operation will be performed in series until all are complete.
Here is an outline for the solution:
// Create a new queue to hold network operations.
self.operationQueue = [[NSOperationQueue alloc] init];
self.operationQueue.maxConcurrentOperationCount = 1;
// Split the large array into chunks of 20 items each.
NSInteger chunkSize = 20;
NSInteger i = 0;
NSInteger total = [lowMArray count];
while (i < total) {
NSInteger j = i;
NSMutableArray *chunk = [NSMutableArray alloc] init];
while (j < i + chunkSize - 1 && j < total) {
[chunk addObject:lowMArray[j]];
j++;
}
MyOperation *myOperation = [[MyOperation alloc] initWithArray:chunk];
self.operationQueue.addOperation(myOperation)
i += chunkSize;
}
MyOperation.h:
#interface MyOperation : NSOperation
- (instancetype)initWithArray:(NSArray *)chunk;
#property NSArray *chunk;
#end
MyOperation.m:
#implementation MyOperation
- (instancetype)initWithArray:(NSArray *)chunk
{
if (self = [super init]) {
self.chunk = chunk;
}
return self;
}
- (void)main
{
// Create Json data from lowMArray
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.chunk
options:NSJSONWritingPrettyPrinted
error:nil];
// Construct post request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/lows", _silServerBaseUrl]]];
request = [self applyAuth:request];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
// Send post request
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
// NSLog(#"Response Failed!");
} else {
// NSLog(#"Response Success!");
}
}];
[dataTask resume]; // runs task
}
#end
AFNetworking has support for its own NSOperation subclass in AFHTTPRequestOperation. An example can be found here. Also, the AFNetworking GitHub repository has an example for batch operations.
Based on your revised question, setting the completion block of each AFHTTPRequestOperation to handle the response and error can help to debug the problem.
Here is how it is done:
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSString* decodedResponse = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"response %#", decodedResponse);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(#"error %#", error);
}];
It would be inserted after AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];.

how to set button enable and disbale in ios app?

i am creating 2 buttons one for like and one for dislike when i click like button its disable and also disable dislike button same time.and so on. and its not change when i am run the application second time. i am implemented for that its work but problem is that when i run my application second time once again that button enable. problem is that i don't want that button same button enable.please help me what is the problem in my code
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:102/255.0
green:102/255.0 blue:204/255.0 alpha:1.0];
self.navigationController.navigationBar.titleTextAttributes =
#{NSForegroundColorAttributeName : [UIColor whiteColor]};
smsdisplaytext.editable=NO;
smsdisplaytext.backgroundColor= [UIColor colorWithRed:102/255.0 green:102/255.0
blue:204/255.0 alpha:1.0];
self.navigationItem.title=#"Insta SMS";
[ self getSmsData];
[self smsdisplay];
[self getLike];
}
-(void)sendlike
{
NSURL *url = [NSURL URLWithString:
#"http://sms.instatalkcommunications.com/apireq/AddRatingForSMS"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[NSString stringWithFormat:#"%d",1] forKey:#"t"];
[request setPostValue:#"admin" forKey:#"h"];
[request setPostValue:[NSString stringWithFormat:#"%#",self.Id] forKey:#"cid"];
[request setPostValue:[NSString stringWithFormat:#"%d",1234567890] forKey:#"token"];
[request setPostValue:#"test#test.com" forKey:#"email"];
[request setTag:2];
[request setPostValue:#"true" forKey:#"like"];
[request setDelegate:self];
[request startAsynchronous];
}
-(void)senddislike
{
NSURL *url = [NSURL URLWithString:
#"http://sms.instatalkcommunications.com/apireq/AddRatingForSMS"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[NSString stringWithFormat:#"%d",1] forKey:#"t"];
[request s etPostValue:#"admin" forKey:#"h"];
[request setPostValue:[NSString stringWithFormat:#"%#",self.Id] forKey:#"cid"];
[request setPostValue:[NSString stringWithFormat:#"%d",1234567890] forKey:#"token"];
[request setPostValue:#"test#test.com" forKey:#"email"];
[request setPostValue:#"false" forKey:#"Like"];
[request setTag:3];
[request setDelegate:self];
[request startAsynchronous];
}
- (void) requestFinished:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
responseString = [request responseString];
NSLog(#"%#",responseString);
if(request.tag==1)
{
SBJsonParser *parser = [[SBJsonParser alloc] init] ;
NSArray *jsondata = [parser objectWithString:responseString];
NSLog(#"%#",jsondata);
for (NSObject* item in jsondata)
{
likelabel.text = [[item valueForKey:#"Liked"] stringValue];
dislikelabel.text = [[item valueForKey:#"Disliked"] stringValue];
}
}
else if(request.tag==2)
{
[self getLike];
}
/////// getting comment
else if(request.tag==4)
{
// get comments
SBJsonParser *parser = [[SBJsonParser alloc] init] ;
NSMutableArray *jsondata = [parser objectWithString:responseString];
for(int i=0;i<jsondata.count;i++)
{
NSObject *temp = [jsondata objectAtIndex:i];
NSMutableDictionary *message = [[NSMutableDictionary alloc] init];
message[kMessageContent]=[temp valueForKey:#"Comment"];
message[#"Timestamp"]=[self dateWithJSONString:[temp valueForKey:#"CreatedDate"]];
last=[[temp valueForKey:#"Id"] integerValue];
[_chatController addNewMessage:message];
}
}
else
{
////post comment
[self getComment];
}
}
//this method for getting like and dislike
-(void)getLike
{
NSString *url = [NSString
stringWithFormat:#"http://sms.instatalkcommunications.com/apireq/GetRatingsForSMS?
t=1&h=admin&cid=%#&token=1234567890&email=test#test.com",self.Id];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setRequestMethod:#"GET"];
[request setTag:1];
[request setDelegate:self];
[request startAsynchronous];
}
// here for like button
- (IBAction)btnlike:(id)sender
{
NSLog(#"keypress");
[self sendlike];
[self getLike];
UIButton *btnlike = (UIButton *) sender;
btnlike.enabled = NO;
UIButton *btndislike = (UIButton *) sender;
btndislike.enabled = NO;
}
//here i am action for dislike button
- (IBAction)btndislike:(id)sender
{
NSLog(#"keypress");
[self senddislike];
[self getLike];
UIButton *btndislike = (UIButton *) sender;
btndislike.enabled = NO;
_btnlike.enabled = NO;
}
#end
As I'm not an native english speaker, I hope I've understood correctly what you are trying to achieve.
If I understand correctly, You have a 'Like' and 'Dislike' buttons, and when the user presses on one of them, you want both to be disabled,
Which is working correctly for the current run.
But, if I understand correctly, the next time the app runs, the buttons are 'reset' to be enabled, and you don't want that,
You want the button be disabled every time the app runs.
If I did understood you correctly, the way to 'save' state of objects is using the NSUserDefaults.
You might have a better way to implement it than my example below, but it should do the trick, and also give you a better understanding on how to implement it, incase you need to modify my code.
Add the following method:
-(void)disableButtons {
[[NSUserDefaults standardUserDefaults] setBool: YES forKey: #"buttonsDisabled"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
now, at the end of the 'Like' and 'Dislike' buttons, just call the following methods by adding to your code:
[self disableButtons]
Now, add the following to viewDidLoad:
// someplace in viewDidLoad
BOOL bottunsDisabled = [[NSUserDefaults standardUserDefaults] boolForKey: #"buttonsDisabled"];
if(buttonsDisabled) {
self.btndislike.enabled = NO;
self.btnlike.enabled = NO;
}
The buttons defaults state are enabled, so the above code will change them, incase they have been disabled in previous runs.
Note that I also assumed you have a reference to the buttons (I assume you've created them in interface builder), if not, just create a property/ivar that will hold a reference to them.
And as Ian MacDonald mentioned above, in the 'Like' button method, you are disabling only the 'Like' button twice, and not disabling the 'Dislike' button.
In order to fix it, change the code to the following (again, I assume you have some sort of reference to both of them):
- (IBAction)btnlike:(id)sender
{
NSLog(#"keypress");
[self sendlike];
[self getLike];
self.btnlike.enabled = NO;
self.btndislike.enabled = NO;
[self disableButtons];
}
As I've said above, I'm not an native english speaker,
So I hope my answer was clear enough.
If something isn't clear, just tell me and I'll try to rephrase it.
Good luck mate!

IOS Creating Utility Class For NSURL

I have a project I am working on that has a number of different news feeds and announcement boards that displays post from various sources. Currently I have the code for the like, delete and flag buttons in methods contained in each class file for the views that display the feeds. I have been trying to craft a utility class that allows me to place the code for the three functionalities listed above in one object to be used throughout the project. I have done the exact same type of thing in C++ or Java, but am having issues reproducing it in objective-c. The like, delete and flag buttons use the NSURL libraries to interact with the web service. Bellow is an example of one of the methods I am trying to implement in the utility class, and is the code used to be implemented in the like buttons:
+ (void)btnLikeAction:(UIButton *)btnLike userIdString:(NSString *)userId contentSource:(NSString *)sourceId cellUsed:(NewsfeedCell *)cell dataForCell:(Post *)post
{
BOOL hasLiked = post.hasLiked;
UILabel *likeLabel = cell.likeCount;
NSString *pId = post.postId;
if (hasLiked)
{
[btnLike setEnabled:NO];
NSString *url = [NSString stringWithFormat: #"http://192.155.94.183/api/v1/likes/unlike/%#/%#/%#/", sourceId, pId, userId];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
int localCount = [likeLabel.text intValue];
localCount--;
likeLabel.text = [NSString stringWithFormat:#"%i", localCount];
post.likeCount = [NSString stringWithFormat:#"%i", localCount];
post.hasLiked = NO;
[btnLike setEnabled:YES];
}
else
{
[btnLike setEnabled:NO];
NSError *err = nil;
NSDictionary *likeData = [NSDictionary dictionaryWithObjectsAndKeys:
userId, #"user_id",
pId, #"source_id",
sourceId, #"source",
nil];
NSData *JSONLike = [NSJSONSerialization dataWithJSONObject:likeData options:NSJSONWritingPrettyPrinted error:&err];
NSString *url = #"http://192.155.94.183/api/v1/likes.json";
NSURL *URL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [JSONLike length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:JSONLike];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
int localCount = [likeLabel.text intValue];
localCount++;
likeLabel.text = [NSString stringWithFormat:#"%i", localCount];
post.likeCount = [NSString stringWithFormat:#"%i", localCount];
post.hasLiked = YES;
[btnLike setEnabled:YES];
}
}
This code uses a web service to update the number of likes for a specific piece of content. It works when the method is placed into the individual ViewController class files, but when I try to make a utility class with the individual methods I run into issues with the didReceiveAuthenticationChallenge, didReceiveResponse, didReceiveData and connectionDidFinishLoading methods not being called. Originally, I assumed that the delegate methods would be called in the file that that the utility methods were called in. But that was not the case. When I implemented the method definitions in the actual utility class, the methods still weren't called. I did some research on the topic and looked into this article but found I was unable to find substantial resources that helped my specific situation. How do I set up my utility class? I can post the full code of the utility if needed.
As #serrrgi already said, the problem is that btnLikeAction:... is a class method, so that self is the class itself. You have the following options:
Make all delegate methods class methods, e.g.
+ (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
}
Create an instance of your Utility class and use that as delegate:
YourClass *u = [[self alloc] init];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:u];
Use sendAsynchronousRequest:..., which does not need a delegate:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data != nil) {
NSLog(#"success");
} else {
NSLog(#"error: %#", error);
}
}];

ASIHTTPRequest does not update progress

update
I think the problem is with the networkQueue. When I replace [self.networkQueue addOperation:request] with [request startAsynchronous] or [request startSynchronous], it works.
I update the code to make it more clear.
original
I use ASIHTTPRequest to upload a file of json with encoded image (or [request setFile:imagefile...]), but I cannot update the progress.
I got only one output: value: 1.000000, which means the uploads finished.
incrementUploadSizeBy was never triggered.
I have searched online a lot but still cannot find a answer. Here is my code.
+ (ASIEngine *)sharedInstance {
static ASIEngine *sharedInstance = nil;
static dispatch_once_t pred;
dispatch_once(&pred, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (id)init {
if (self = [super init]) {
_networkQueue = [ASINetworkQueue queue];
[_networkQueue setMaxConcurrentOperationCount:MAX_CONCURRENT_OPERATION_COUNT];
[_networkQueue setDelegate:self];
[_networkQueue go];
}
return self;
}
- (void)upload:(NSString *)imageJsonString onCompletion:(void(^)(NSString *responseString))onCompletion onFailed:(void(^)(NSError *error))onFailed {
__unsafe_unretained __block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:UPLOAD_URL]];
[request setShowAccurateProgress:YES];
[request setUploadProgressDelegate:self];
[request setPostValue:imageJsonString forKey:#"imageString"];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
onCompletion(responseString);
}];
[request setFailedBlock:^{
onFailed([request error]);
}];
[self.networkQueue addOperation:request];
}
#pragma mark - ASIProgressDelegate
- (void)setProgress:(float)newProgress {
NSLog(#"value: %f", newProgress);
}
- (void)request:(ASIHTTPRequest *)request incrementUploadSizeBy:(long long)newLength {
NSLog(#"data length: %lld", newLength);
}
If you are uploading a string, you probably have so little data to upload (as opposed to when uploading a picture), that it uploads everything in one step. You could try reading a huge string from a file and see what happens.

Resources