How to migrate AFHTTPClient, Afnetworking 1.0 to 2.0 - ios

My problem is that I have a old code and I dont know how to change it.
I had 1 class called API (AFHTTPClient) I have problems with 2 methods because I dont know how to put them in 2.0:
This:
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock
{
NSMutableURLRequest *apiRequest =
[self multipartFormRequestWithMethod:#"POST"
path:kAPIPath
parameters:params
constructingBodyWithBlock: ^(id formData) {
//TODO: attach file if needed
}];
AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:#"error"]);
}];
[operation start];
}
and this:
#pragma mark - init
//intialize the API class with the destination host name
-(API*)init
{
//call super init
self = [super init];
if (self != nil) {
//initialize the object
user = nil;
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
// Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
[self setDefaultHeader:#"Accept" value:#"application/json"];
}
return self;
}
I do a new class called Api, now (AFHTTPRequestOperationManager) is good?
I try with this, but I dont have idea
-(API*)init
{//call super init
self = [super init];
//initialize the object
if (self != nil) {
//initialize the object
user = nil;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFJSONRequestSerializer *a=[AFJSONRequestSerializer serializer];
[a setValue:#"Accept" forHTTPHeaderField:#"application/json"];
[a setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[a setValue:#"content-Type" forHTTPHeaderField:#"text/html"];
[a setValue : # "text / html; charset = UTF-8" forHTTPHeaderField : # "Content-Type" ];
}
return self;
}
-(void)commandWithParams:(NSMutableDictionary*)params onCompletion:(JSONResponseBlock)completionBlock
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = params;
NSURL *filePath = [NSURL URLWithString:#"http://162.243.199.147/mujeresquecorren/iReporter/index.php"];
[manager POST:#"api" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"api" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
NSMutableURLRequest *apiRequest = [NSMutableURLRequest requestWithURL:filePath];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// operationManagerInstance.requestSerializer = requestSerializer;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:apiRequest];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://162.243.199.147/mujeresquecorren/iReporter/index.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:nil];
// AFJSONRequestOperation* operation = [[AFJSONRequestOperation alloc] initWithRequest: apiRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//success!
completionBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure :(
completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:#"error"]);
}];
[operation start];
}
and this is one of the errors:
rror: Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0xa64f980 {NSErrorFailingURLStringKey=api, NSErrorFailingURLKey=api, NSLocalizedDescription=unsupported URL, NSUnderlyingError=0xa782e10 "unsupported URL"}
Please help, im going to be crazy with that and I need that my code works in my app!
Thanks a lot!!!!

It's all there in the error message. "api" isn't a valid URL. You need to either specify an absolute URL, or initialize your request operation manager with a baseURL, using initWithBaseURL:.

Related

Uploading image to server (Objective C)

I try to send image as byte[] to server.
When I sent it from POST-MAN, like html will send files, it works.
But when I try to send from Objective C code, it sents different array of bytes:
+ (void)uploadPhoto:(UIImage*)photo withCompletionBlock:(responceBlock)block
{
AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];
NSData* imageData = UIImageJPEGRepresentation(photo, 6);
[manager.requestSerializer setValue:[UserDefaultsHelper getToken] forHTTPHeaderField:#"X-AUTH-TOKEN"];
AFHTTPRequestOperation* op = [manager POST:#"http://localhost:8080/image/save"
parameters:#{}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"ParamFiles" fileName:#"photo2131231.jpg" mimeType:#"image/jpeg"];
}
success:^(AFHTTPRequestOperation* operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
}
failure:^(AFHTTPRequestOperation* operation, NSError* error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
}
Answer: Sorry for stupid question. Problem, that on server I handle just binary image. Objective C code send me multipart files, so it contains binary image with filename, mimetype and other fields. I converted everything to bytes and tried to save this like image. Of course server can't do that.
Try this out
+ (void)uploadPhoto:(UIImage*)photo withCompletionBlock:(responceBlock)block
{
AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];
NSData* imageData = UIImageJPEGRepresentation(photo, 6);
[manager.requestSerializer setValue:[UserDefaultsHelper getToken] forHTTPHeaderField:#"X-AUTH-TOKEN"];
NSMutableURLRequest * request = [manager.requestSerializer
multipartFormRequestWithMethod:#"POST"
URLString:#"http://localhost:8080/image/save"
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
UIImage *image = [page.imageVersionObject imageForVersion:page.imageVersionObject.selectedVersion];
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, (CGFloat)0.85)
name:#"file"
fileName:#"fileName.jpg"
mimeType:#"image/jpeg"];
}
}
error:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//SUCCESS HERE!!!
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//FAILURE HERE
}];
[manager.operationQueue addOperation:operation];
}
Do not forget to use your filename and name.... I have used mine for testing

The network connection was lost.NSURLErrorDomain Code=-1005

Could anyone help on this?.I am using AFNetworking(1.x) POST method in my app.But frequently i am getting:
'The network connection was lost' error.Error Domain=NSURLErrorDomain Code=-1005 “The network connection was lost.”
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFHTTPResponseSerializer serializer];
op.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
op.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
[self SuccessResponse:responseObject:reqType];
NSLog(#"JSON responseObject: %# ",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Make sure you have working internet connection.
Try to use below code.
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
NSDictionary *params ; // Pass your POST Parameters here by creating the Dictionary.
[manager POST:#"your api here" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Request failed
// To get failed response data use operation.responseObject
NSLog(#"like request failed %#", error);
}];
Hope this will help you.

How to make an HTTP request with AFNetorking and NSURLRequest?

I am trying to use AFHTTPRequestOperationManager to make an HTTP request. I need to use AFHTTPRequestOperationManager because I want to be able to cancel all operations if necessary. I can't get this working for some reason. The completion blocks aren't called. Am I missing something?
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://twitter.com/%#", username]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"MyUserAgent (iPhone; iOS 7.0.2; gzip)" forHTTPHeaderField:#"User-Agent"];
[request setHTTPMethod:#"GET"];
[self.manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if ([html containsString:#"var h = decodeURI(l.hash.substr(1)).toLowerCase();"]) {
completion(YES, nil);
} else {
completion(NO, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completion(NO, error);
}];
This is working code, you need to use GET or POST method there.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"email":emailfield.text};
[manager GET:#"http://example.com/api" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
While everyone else is right -- you should be using the modern AFNetworking constructs instead of the legacy features -- there is a quick way to get done what you're looking to get done.
By the looks of it, the method - (??? *) HTTPRequestOperationWithRequest:success:failure likely returns an AFHTTPRequestOperation. If I'm correct, you just need to actually start the operation. See below for your code, corrected.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://twitter.com/%#", username]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"MyUserAgent (iPhone; iOS 7.0.2; gzip)" forHTTPHeaderField:#"User-Agent"];
[request setHTTPMethod:#"GET"];
AFHTTPRequestOperation *op = [self.manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if ([html containsString:#"var h = decodeURI(l.hash.substr(1)).toLowerCase();"]) {
completion(YES, nil);
} else {
completion(NO, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
completion(NO, error);
}];
[op start];
HTTPRequestOperationWithRequest method returns AFHTTPRequestOperation. You have to add it to some operation queue to start it. For example
AFHTTPRequestOperation *operation = [self.manager HTTPRequestOperationWithRequest:request .........
[[NSOperationQueue currentQueue] addOperation:operation];
You can use AFHTTPSessionManager which is a little better than AFHTTPRequestOperationManager and cancel requests using method cancel of NSURLSessionDataTask. You can find some code examples here - AFNetworking 2.0 cancel specific task
Check this will work
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", nil];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];

Trying to make a function to handle AFNetworking

I'm trying to make a function that I'll call to handle the AFNetworking JSON parse.
Here is my code:
- (int)startParseWithParameters:(NSDictionary*)incomingParameters andUrlAdress:(NSString*)urlAdress;
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = incomingParameters;
[manager POST:urlAdress parameters:parameters success:^
(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *recivedErr = responseObject[#"error"];
_errValue = [recivedErr intValue];
NSLog(#"JSON: %d", _errValue);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
return _errValue;
}
I want the function to return 0 or 1, then I'll know if there is an error or not.
Right now it always return 0.
When I try to return in the success block I get a compiler error.
What could cause this problem?
The succes block is handled async so you should just call a method in the block:
- (void)startParseWithParameters:(NSDictionary*)incomingParameters andUrlAdress:(NSString*)urlAdress {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = incomingParameters;
__weak typeof(self) weakSelf = self;
[manager POST:urlAdress parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *recivedErr = responseObject[#"error"];
[weakSelf didReceiveResponse:[recivedErr integerValue];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
-(void)didReceiveResponse:(NSInteger)status {
}

Afnetworking 2 with parameters

i am really new to IOS developments..i just want to get some JSON response from my web service. when i searched about it i found AFnetworking is good for that. so i downloaded it and did a sample application. but i need to pass some parameters to the service . my service takes two parameters [username and password]. my url like this
http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser
can anyone please give me some code sample how to pass my parameters to this service to get json response ?
i have tried this code.. but it wont take parameters.. some people telling about AFHTTPClient.. but im using AFN 2.0.. there is no class call AFHTTPCLient here .. i'm so conduced here....please help me
NSURL *url = [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/textsearch/json?query=restuarants+in+sydney&sensor=false&key=AIzaSyDn9a-EvJ875yMxZeINmUP7CwbO9YT1w2s"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
self.googlePlaces = [responseObject objectForKey:#"results"];
[self.tableView reloadData];
// NSLog(#"JSON RESULT %#", responseObject);
self.weather = (NSDictionary *)responseObject;
self.title = #"JSON Retrieved";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
EDIT :
i have sloved my problem using below code segments...
NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:#"your full url goes here"
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
}
];
Try this
-(void)login
{
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithCapacity:3];
[dict setObject:_usernameTextField.text forKey:#"userName"];
[dict setObject:_passwordTextField.text forKey:#"password"];
AFHTTPClient *client=[[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:#""]];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefaultHeader:#"Accept" value:#"application/json"];
client.parameterEncoding = AFJSONParameterEncoding;
[client postPath:#"GetValidUser" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *op=(NSDictionary *)responseObject;
NSLog(#"%#",op);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:MESSAGE_EN message:#"Unable to login. Please try again." delegate:self cancelButtonTitle:OK_EN otherButtonTitles:nil, nil];
[alert show];
NSLog(#"error.localizedDescription %#",error.localizedDescription);
}];
}
Note : Please do fill the fields with proper values and try.
dict is the Input postdata
I got this one from somewhere in SO question. See this:
- (IBAction)loginButtonPressed {
NSURL *baseURL = [NSURL URLWithString:#"http://myweb.mobile.com/WebServices/AppointmentService.asmx"];
//build normal NSMutableURLRequest objects
//make sure to setHTTPMethod to "POST".
//from https://github.com/AFNetworking/AFNetworking
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[usernameTextField text], kUsernameField,
[passwordTextField text], kPasswordField,
nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"http://myweb.mobile.com/WebServices/AppointmentService.asmx/GetValidUser" parameters:params];
//Add your request object to an AFHTTPRequestOperation
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc]
initWithRequest:request] autorelease];
//"Why don't I get JSON / XML / Property List in my HTTP client callbacks?"
//see: https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
//mattt's suggestion http://stackoverflow.com/a/9931815/1004227 -
//-still didn't prevent me from receiving plist data
//[httpClient registerHTTPOperationClass:
// [AFPropertyListParameterEncoding class]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation,
id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
}];
//call start on your request operation
[operation start];
[httpClient release];
}
Hope this helps .. :)
EDIT
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding]
name:#"email"];
[formData appendPartWithFormData:[pass dataUsingEncoding:NSUTF8StringEncoding]
name:#"password"];
// etc.
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Use below code
NSDictionary *paramDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"first_Object",#"first_Key",#"second_Object",#"second_Key" nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"YOUR_URL_STRING" parameters:paramDictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {Success responce} failure:^(AFHTTPRequestOperation *operation, NSError *error) {failure responce}];
if you want you can set
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;

Resources