AFNetworking JSON Request, neither success nor error block called - objective-c

I'm trying to learn AFNetworking so have written a simple block. I'm trying to retrieve & log the json from the site url below.
NSString *string =
#"http://transportapi.com/v3/uk/bus/stop/490012745J/live.json?api_key=6ee115459cbeccdb902b14d39b61330d&app_id=9deefeb1&group=route";
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *mydict = (NSDictionary *)responseObject;
NSString *key;
for(key in mydict){
NSLog(#" key %#", key);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"ERROR");
}];
But neither the success or the failure block is being called. Can someone point out what I've done wrong?

You're not actually firing the operation you need to add
[[NSOperationQueue mainQueue] addOperation:operation];

Related

AFNetworking 1.x to 3.x migration - get download progress?

I need to download image with progress bar. This is what I've got for in AFNetworking 1.x which is not working for AFNetworking 3.x.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.mediaItem.media_item_hd_url]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFImageResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
UIImage *image = responseObject;
_image = image;
[self.delegate browserItem:self loaded:1.0 finished:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { }];
[op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
CGFloat progress = ((CGFloat)totalBytesRead)/((CGFloat)totalBytesExpectedToRead);
[self.delegate browserItem:self loaded:progress finished:NO];
}];
[[NSOperationQueue mainQueue] addOperation:op];
Finally this is what I could come up with, which is not complete. I have no idea how to use progress in code block.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.mediaItem.media_item_hd_url]];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
// UIImage *image = response;
// _image = image;
[self.delegate browserItem:self loaded:1.0 finished:YES];
}];
[downloadTask resume];
You can get best framework RSNetworkKit which handles all the network call with an ease. It has internally implemented AFNetworking 3.0. It'll gives you download progress in single method either you upload, download.
It has also an enhanced method to show progress on UIImageView.
You can find it here. https://github.com/rushisangani/RSNetworkKit

Creating dependencies between operations when using AFHTTPRequestOperation

I'm working with AFNetworking (2.4.1) in a mac application. I'm hoping to add my own block operation that is for after completion of all of the other operations (which are AFHTTPRequestOperation). I have tried adding dependencies between the completionOperation and the others, but the completionOperation block still executes before the others have completed with success or failure.
A cut down version of the code that illustrates the basics is below. Is anyone able to suggest how to make this work? Thanks.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
NSBlockOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(#"All operations complete");
}];
NSMutableURLRequest *request1 = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"GET" URLString:[[NSURL URLWithString:#"https://api.parse.com/1/classes/SomeClass"] absoluteString] parameters:nil error:nil];
AFHTTPRequestOperation *operation1 = [manager HTTPRequestOperationWithRequest:request1 success:
^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"operation 1 success");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"operation 1 failure");
}];
NSMutableURLRequest *request2 = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"GET" URLString:[[NSURL URLWithString:#"https://api.parse.com/1/classes/OtherClass"] absoluteString] parameters:nil error:nil];
AFHTTPRequestOperation *operation2 = [manager HTTPRequestOperationWithRequest:request2 success:
^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"operation 2 success");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"operation 2 failure");
}];
[completionOperation addDependency:operation1];
[completionOperation addDependency:operation2];
[manager.operationQueue addOperation:operation1];
[manager.operationQueue addOperation:operation2];
[manager.operationQueue addOperation:completionOperation];
- (void) test3:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
// block 1
NSString *string = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *urll = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:urll];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"OPERATION 1 %#",responseObject );
test_Sync = #"done";
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
test_Sync = #"faile"; }];
//block 2
NSString *string2 = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *urll2 = [NSURL URLWithString:string2];
NSURLRequest *request2 = [NSURLRequest requestWithURL:urll2];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request2];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation2, id responseObject) {
// Print the response body in text
NSLog(#"Response: OPERATION 2 %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation2, NSError *error) {
NSLog(#"Error: %#", error);
}];
// Add the operation to a queue
// It will start once added
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
// Make operation2 depend on operation1
[operation addDependency:operation2];
[operationQueue addOperations:#[operation, operation2] waitUntilFinished:YES];
}

Upload PowerPoint via AFNetworking gets corrupt

I receive a successfully response when uploading a PowerPoint via the below code. It does get upload but the file is corrupt. When opening the corrupt file on the server via PowerPoint I get this message:
"PowerPoint found a problem with content in filename.pptx. PowerPoint can attempt to repair the presentation."
- (void)updateDocument:(NSString *) path parameters:(FileUploadParameters*)para success:(void (^)(void))success failure:(void (^)(NSError *error))failure
{
_postData = nil;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:[ConfigurationUtil objectForKey:#"baseURL"]]];
_postData = [NSMutableData dataWithContentsOfFile:[path stringByStandardizingPath]];
_postData = [NSMutableData dataWithContentsOfFile:[path stringByStandardizingPath] options:NSDataReadingMapped error:nil];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:HTTP_METHOD_POST
path:[self getQueryString:path parameter:para]
parameters:nil
constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:_postData
name:[[path lastPathComponent] stringByDeletingPathExtension]
fileName:[[path lastPathComponent] stringByDeletingPathExtension] mimeType:#"application/powerpoint"];
}];
[request addValue:[NSString stringWithFormat:#"WRAP access_token=%#",[Tenant loadSharedTenantInstance].authToken] forHTTPHeaderField:#"Authorization"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
if (success)
success();
}
failure:^(AFHTTPRequestOperation* operation, NSError* error)
{
if (failure)
failure(error);
}
];
[operation start];
}
Your AFNetworking code looks fine. I don't think that's the culprit.
You can use the cmp command line tool to compare the two files (the original and the upload) byte-for-byte and see if there's a difference. I think there won't be.
More likely: it's a misleading error message, and it's actually a permissions issue on the computer with Powerpoint installed, as outlined in this Microsoft Knowledge Base article.
The below code corrects the problem. It appears that appendPartWithFileData was causing the issue. It changes the filesize and that seemed to register the file as corrupt.
_postData = nil;
_postData = [NSMutableData dataWithContentsOfFile:[path stringByStandardizingPath]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
NSString *queryString =[self getQueryString:path parameter:nil];
[request setURL:[NSURL URLWithString:queryString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:_postData];
[request addValue:[NSString stringWithFormat:#"WRAP access_token=%#",[Tenant loadSharedTenantInstance].authToken] forHTTPHeaderField:#"Authorization"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
if (success)
success();
}
failure:^(AFHTTPRequestOperation* operation, NSError* error)
{
if (failure)
failure(error);
}
];
[operation start];

Authenticating Users using AfNetworking

I'm trying to authenticate users, but my app keeps on crashing with error 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: urlRequest' what am I doing wrong?
Below is my code
-(IBAction)btnLogin:(id)sender
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager alloc];
NSDictionary *parameters = #{#"email": email.text, #"pass": pword.text};
NSString *str = #"http://www.blablablabla/api2/user.php?type=login";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:#"POST" URLString:str parameters:parameters];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//[operation setCredential:credential];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[manager.operationQueue addOperation:operation];
}
You seem to be alloc-ing the AFHTTPRequestOperationManager but does it ever get init'ed?
Also, check the request for nil before passing it to the AFHTTPRequestOperation.
Checking parameters and alloc'ed/created instances for nil can help you tell IMMEDIATELY where a problem is.
Hope this helps.

Trying to read html page from a web site using AFNetworking 2.0

I'm trying to have my app load an HTML web page into a "responseObject" that I can later parse.
Here is my code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/xhtml+xml"];
NSDictionary *parameters = #{#"ghinno": #"1151213"};
[manager GET:#"http://m.ghin.com/HLR.aspx" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"HTTP: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
...and this is the output. I should be seeing the html from the webpage. Can you help me understand what I am doing wrong?
Ah, the answer lies below...
Essentially, it was an encoding / decoding of the response object that was causing my issues. Here is the final solution: (notice the line beginning with "NSString)...
NSURL *URL = [NSURL URLWithString:#"http://m.ghin.com/HLR.aspx?ghinno=1151213"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[op start];