I am learning AFNetworking kit. I followed this tutorial. Now I stuck at comment 2 see code below AFHTTPRequestOperation.
I imported AFNetworking using cocoapods.
Here is my code:
- (IBAction)jsonTapped:(id)sender{
// comment 1
NSString *string = [NSString stringWithFormat:#"%#weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// comment 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// comment 3
self.weather = (NSDictionary *)responseObject;
self.title = #"JSON Retrieved";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// comment 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// comment 5
[operation start];
}
Now getting error at compile time see screen shot:
Please make sure that you included AFNetworking properly inside your project before you import any of the AFNetworking class. Probably you have not imported the kit properly.
Dont use UIAlertView which is deprecated iOS 9 use UIAlertController see code below.
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Title" message:#"text mssg" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:#"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
// Ok action code here
}];
UIAlertAction *otherAction = [UIAlertAction actionWithTitle:#"Other" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
// Other action code here
}];
[alert addAction:okAction];
[alert addAction:otherAction];
[self presentViewController:alert animated:YES completion:nil];
You can use AFHTTPRequestOperationManager
- (void)apiRequestForPOSTWithServiceName:(NSString *)serviceName andParameters:(NSDictionary *)parameter withCompletion:(void(^)(id response, BOOL isSuccess))completion
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSString *url = [NSString stringWithFormat:#"%#%#", BASE_URL, serviceName];
[manager POST:url parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(#"JSON: %#", responseObject);
completion(responseObject,YES);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
completion(error,NO);
}];
}
Happy coding...!!
Related
I've to add google autocomplete api in my app but I don't know. I also getting "INVALID REQUEST". I also check developer.google.com but I can't find any solution. I am using AFNetwrok.
Here is my code
NSString *strURL = [NSString stringWithFormat:#"%#key=%#",AutoComplete_URL,GOOGLE_KEY];
NSDictionary *params = #{#"input" : [#"Paris" stringByReplacingOccurrencesOfString:#" " withString:#"+"],#"sensor":#"true"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:strURL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
[APPDELEGATE hideLoadingView];
if ([[responseObject valueForKey:#"status"] isEqualToString:#"OK"]) {
arrAutocomplete = [[responseObject valueForKey:#"predictions"] valueForKey:#"description"];
NSLog(#"AUTO: %#", arrAutocomplete);
}
else{
// [APPDELEGATE showpToastWithTitle:[response valueForKey:#"msg"]];
//[self.tableView setHidden:YES];
}
}
else{
[APPDELEGATE hideLoadingView];
[APPDELEGATE showToastWithTitle:#"Please check your internet connection"];
}
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[APPDELEGATE hideLoadingView];
[APPDELEGATE showToastWithTitle:#"Something going wrong"];
}];
OUTPUT :-
JSON:
{
predictions = (
);
status = "INVALID_REQUEST";
}
i got it.
NSString *string = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/autocomplete/json?key=%#&types=geocode&input=%#",GOOGLE_KEY,address];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
NSLog(#"%#",responseObject);
}
} 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];
I am using AFNetworking Framework for calling API and sometimes I am not getting any response from server while API call:
Here is my code snippet:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager.requestSerializer setTimeoutInterval:timeOutInterval];
[manager POST:[NSString stringWithFormat:#"%#%#",MainUrl,apiName] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *arrData = responseObject;
NSLog(#"%#",arrData);
NSString *strCode = [NSString stringWithFormat:#"%#",[arrData valueForKey:#"success"]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[SVProgressHUD dismiss];
NSLog(#"Error: %#", manager);
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Message" message:#"Please check your internet connection" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}];
I get below error :
Error: <AFHTTPRequestOperationManager: 0x80010ce0, baseURL: (null), operationQueue: <NSOperationQueue: 0x80010ca0>{name = 'NSOperationQueue 0x80010ca0'}>
Any help will be appreciated.
In ios 9.1
AFNetworking 2.5
Hi i am beginner in Ios and in my project there is facility for users "ForGotPassword" request
For this i have written some code but that is not working
i.e is objectFromJSONString response shows like -->Message: "No HTTP resource was found that matches the request URI "my url."
what did i do here wrong ,is it my problem or server side problem? please help me
my code:-
- (IBAction)submitBtnClicked:(id)sender {
NSLog(#"password ---->>> %#",self.MedicalIdTxt.text);
NSString *urlStr = [NSString stringWithFormat:#"my url"];
NSLog(#"urlStr --->>> %#",urlStr);
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setRequestMethod:#"POST"];
[request setPostValue:self.MedicalIdTxt.text forKey:#"MedicaidId"];
[request setDelegate:self];
[request startAsynchronous];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSLog(#"requestFinished");
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"%#",request);
NSString *receivedString = [request responseString];
NSLog(#"receivedString %#",receivedString);
NSDictionary * jsonObj=[[NSDictionary alloc]init];
jsonObj = [receivedString objectFromJSONString];
NSLog(#"jsonObj result is%#",jsonObj);
NSString *messageStr = [jsonObj objectForKey:#"message"];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"" message:messageStr delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSString *receivedString = [request responseString];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:receivedString message:#"" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
here "jsonObj" not showing response which is coming from services what did i do here wrong?
ASIHTTPRequest is not under maintenance since so long, so use AFNetworking instead:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"your url"
parameters:#{#"color": #"green"}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I have issues with AFNetworking in iOS 8 + UIAlert. in UIAlertView delegate:
(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
I made HTTP Post request, but it never calls AFNetworking success or failure blocks.
I see the HTTP Request call into server Log,
It works in iOS 7.
Code:
- (IBAction)btnAction:(id)sender {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: NSLocalizedString(#"Bla bla bla",nil)
message: NSLocalizedString(#"Bla bla bla",nil)
delegate: self
cancelButtonTitle: NSLocalizedString(#"No",nil)
otherButtonTitles: NSLocalizedString(#"Si",nil), nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
[self sendRequest];
}
}
- (void) sendRequest {
NSDictionary *parameters = #{#"e":#"ecc", #"data": #"ecc2"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
[[manager requestSerializer] setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[[manager requestSerializer] setTimeoutInterval:30];
[manager POST:url parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NEVER call block
NSLog(#"Request success %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// NEVER call block
NSLog(#"Error HTTP: %#\n%#", operation, error);
}];
}
I'm new in iOS Development. I create Upload Image Method with "AFNetworking". And I want to Add UIProgressView when Processing.
Now I use "DejalBezelActivityView" in my Upload Method
"DejalBezelActivityView" is worked but i want to use UIProgressView.
How to do it?
This is Example of my code:
-(void) uploadImage
{
// Set Data to Web API
// NSMutableArray *newPictureData = ...
// WEB API
[PictureClient uploadPictures:newPictureData whenCompleted:^(BOOL success, NSString *data, NSError *error)
{
if (success)
{
[DejalBezelActivityView removeViewAnimated:YES];
UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:#“Complete"
message:#“Upload Cpmplete"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[myAlertView show];
// Do somethings
// ...
}
else
{
[DejalBezelActivityView removeViewAnimated:YES];
// Error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#“Error"
message:errorCode
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}];
[DejalBezelActivityView activityViewForView:self.view withLabel:#“During Picture"];
}
like #StatusReport answered with MBHudProgress
// 1. Create `AFHTTPRequestSerializer` which will create your request.
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
// 2. Create an `NSMutableURLRequest`.
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:#"http://www.myurl.com"
parameters:dataToPost
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"attachment"
fileName:#"myimage.jpg"
mimeType:#"image/jpeg"];
}];
// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"Failure %#", error.description);
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
NSLog(#"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
}];
// 5. Begin!
[operation start];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];