Please, I need help ;
in my ios app, user can create an account by editing a password;
but when this happens I am getting HTTP status 400
I am trying to post the data on the server which asks for JSON format
Here's what I am doing
NSLog(#"user_id: %#", user_id);
NSString *oldPassword = self.txt_mdpss.text ;
NSString *txtmdpss = self.txt_nv_mdpss.text ;
strUrl = [NSString stringWithFormat:#"https://mysite/wp-json/api/v1/user/editpasswd?user_id=%#&old_passwd=%#&new_passwd=%#",user_id,oldPassword,txtmdpss];
strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[manager GET:strUrl parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
[SVProgressHUD dismiss];
NSLog(#"REPOONSE EDITER MOT DE PASSE = %#", responseObject );
if ([responseObject isKindOfClass:[NSArray class]]) {
NSMutableArray *responseArray = responseObject;
} else if ([responseObject isKindOfClass:[NSDictionary class]]) {
NSDictionary *responseDict = responseObject;
NSLog(#"-------------------> Response Editer Profile = %#",responseObject);
//NSString *strIDUser = [[NSString alloc] initWithFormat:#"%#",[responseDict objectForKey:#"user_id"]];
[self dismissViewControllerAnimated:YES completion:nil];
[[NSUserDefaults standardUserDefaults] setObject:#"no" forKey:#"isConnectedFromFB_notHavePsswd"];
Related
I have implemented the google place search API in IOS and enabled the API in the developer console and used the below code but its shows error that "This IP, site or mobile application is not authorized to use this API key. Request received from IP address 122.173.223.114, with empty refer"
After regenerate the API key its shows API key is expired and after sometime its shows the same above errors. Please help someone.
-(void) queryGooglePlaces: (NSString *) googleType {
// Build the url string to send to Google. NOTE: The kGOOGLE_API_KEY is a constant that should contain your own API key that you obtain from Google. See this link for more info:
// https://developers.google.com/maps/documentation/places/#Authentication
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%#&types=%#&sensor=true&key=%#", appDel.objLocationManager.location.coordinate.latitude, appDel.objLocationManager.location.coordinate.longitude, [NSString stringWithFormat:#"%i", appDel.currenDist],googleType, kGOOGLE_API_KEY];
//Formulate the string as a URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responseData {
//parse out the json data
if (responseData==nil) {
}else{
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:#"results"];
//Write out the data to the console.
NSLog(#"Google Data: %#", json);
}
}
I did it with use of AFNetworking class Try this one,
#define kGoogleAutoCompleteAPI #"https://maps.googleapis.com/maps/api/place/autocomplete/json?key=%#&input=%#"
-(void)getAutoCompletePlaces:(NSString *)searchKey
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// set request timeout
manager.requestSerializer.timeoutInterval = 5;
NSString *url = [[NSString stringWithFormat:kGoogleAutoCompleteAPI,GoogleDirectionAPI,searchKey] stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSLog(#"API : %#",url);
[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSDictionary *JSON = responseObject;
predictions = [NSMutableArray array];
// success
AutomCompletePlaces *places = [AutomCompletePlaces modelObjectWithDictionary:JSON];
[arrSuggestionData removeAllObjects];
if (!arrSuggestionData) {
arrSuggestionData = [NSMutableArray array];
}
for (Predictions *pred in places.predictions)
{
[arrSuggestionData addObject:pred.predictionsDescription];
}
[self.Tbl_suggestion reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
This question already has answers here:
AFNetworking multiple files upload
(3 answers)
Closed 6 years ago.
I used Afnetworking in my app,I need to post 5 images to server, 5 images as array, this array was one of my **request parameters.
this is correct way or wrong one, there is any one more performance than it ? -
(IBAction)sPActionButton:(id)sender {
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSString * language=[def objectForKey:#"Language"];
NSString * deviceToken=[def objectForKey:#"dT"];
[par setObject:deviceToken forKey:#"dT"];
NSString *check=[def objectForKey:#"Log"];
[par setObject:check forKey:#"aT"];
//---------------------------------------------
NSString * apiKey=APIKEY;
[par setObject:apiKey forKey:#"aK"];
[par setObject:language forKey:#"lG"];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:10];
for (int x=0; x<_chosenImages.count; x++) {
NSData *imageData = UIImageJPEGRepresentation(_chosenImages[x], 0.5);
NSLog(#"%#",imageData);
NSString *str=[Base64 encode:imageData];
[images addObject:str];
}
NSLog(#"%#",images);
[par setObject:images forKey:#"image[array]"];
if ([self validateAllFields]) {
NSLog(#"par = %#",par);
//-----------------------------------------------
[MBProgressHUD showHUDAddedTo:self.view animated:NO];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[NSString stringWithFormat:#"%#/sellPrp?",BASEURl] parameters:par
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Data"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
[MBProgressHUD hideHUDForView:self.view animated:NO];
}];
}
}
- (void)prepareForImagePosting
{
if (imageCount < self.arrAllPostImages.count)//arrAllPostImages array contains images for posting and imageCount acts as iterator
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; //Prepare the dictionary which contains image for posting
[dict setObject:#"1" forKey:#"upload"];
[dict setObject:[[self.arrAllPostImages objectAtIndex:imageCount]objectForKey:#"SelectedPhoto"] forKey:#"post_image"];
[self postImage:dict];
}
else
return;
}
- (void)postImage: (NSMutableDictionary *)dictPostImages
{
NSError *error = nil;
NSString *url = POSTIMAGELINK;
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setObject:[dictPostImages objectForKey:#"upload"] forKey:#"upload"];
NSData *jsonRequestDict = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonCommand = [[NSString alloc] initWithData:jsonRequestDict encoding:NSUTF8StringEncoding];
NSLog(#"***jsonCommand***%#",jsonCommand);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:jsonCommand,#"requestParam", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (isEnteredInFailureBlock == NO)
{
//here Image is posted
NSData *postPicData=UIImageJPEGRepresentation([dictPostImages objectForKey:#"post_image"], 0.5) ;
[formData appendPartWithFileData:postPicData
name:#"post_image"
fileName:[NSString stringWithFormat:#"image%d.jpg",imageCount]
mimeType:#"image/*"];
}
else
{
}
} success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
NSMutableDictionary *jsonResponseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Response Dictionary:: %#",jsonResponseDict);
if ([[jsonResponseDict objectForKey:#"status"] intValue] == 1)
{
if (isEnteredInFailureBlock == NO)
{
[self.arrSuccessfullyPostedImagesDetails addObject:jsonResponseDict];
if (appDel.successfullImgPostingCount == appDel.totalPostingImagesCount)
{
}
else
{
appDel.successfullImgPostingCount++;
imageCount++;
[self prepareForImagePosting];
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
imageCount = 0;
return;
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Error: %#", error);
isEnteredInFailureBlock = YES;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Posting Unsuccessful" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
// if image is not successfully posted then the server is informed with #"upload" #"0" so that the entire post is deleted from server
NSMutableDictionary *failureDict = [[NSMutableDictionary alloc]init];
[failureDict setObject:#"0" forKey:#"upload"];
[self postImage:failureDict];
}];
}
this is my code. I want to return an array with data after data assign from the web service to the array.I have use block to check.
this is from my header file...
typedef void(^FailureBlock)(NSError *error);
typedef void(^SuccessBlock) (NSMutableArray *responseArray);
this is my implementation file ....
- (void)setupConnectionWithsuccess:(SuccessBlock)success failure:(FailureBlock)failure
{
airportArray = nil;
NSString *airportCode = [NSString stringWithFormat:#"some code"];
NSString *authenticationCode = [NSString stringWithFormat:#"some api"];
NSString *baseurl = [NSString stringWithFormat:#"some url",authenticationCode,airportCode];
// NSString *mainurlString = [NSString stringWithFormat:#""];
// NSURL *mainurl = [NSURL URLWithString:mainurlString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:baseurl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *mainArray = (NSArray *)responseObject;
airportArray = [[NSMutableArray alloc] init];
for (NSDictionary *all in mainArray) {
airports = [all objectForKey:#"Airport"];
[airportArray addObject:airports];
NSLog(#"%#", airports);
}
if(success){
success(airportArray);
}
//NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
UIAlertController *mainAlert = [UIAlertController alertControllerWithTitle:#"Something Wrong!" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:mainAlert animated:YES completion:nil];
}];
}
then after success, I want to return the array from this method.how can I do that
- (NSArray *)returnAll
{
[self setupConnectionWithsuccess:^(NSMutableArray *responseArray) {
} failure:^(NSError *error) {
}];
}
please help me with this.I'm new to iOS Block.
Try as follow here i use id because in id you can pass anyobject
- (void)setupConnectionWithsuccess:(void (^)(id responseObject, NSError *error))completion{
airportArray = nil;
NSString *airportCode = [NSString stringWithFormat:#"some code"];
NSString *authenticationCode = [NSString stringWithFormat:#"some api"];
NSString *baseurl = [NSString stringWithFormat:#"some url",authenticationCode,airportCode];
// NSString *mainurlString = [NSString stringWithFormat:#""];
// NSURL *mainurl = [NSURL URLWithString:mainurlString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:baseurl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *mainArray = (NSArray *)responseObject;
airportArray = [[NSMutableArray alloc] init];
for (NSDictionary *all in mainArray) {
airports = [all objectForKey:#"Airport"];
[airportArray addObject:airports];
NSLog(#"%#", airports);
}
if (completion)
completion(responseObject,nil);
//NSLog(#"%#", responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (completion)
completion(nil,error);
UIAlertController *mainAlert = [UIAlertController alertControllerWithTitle:#"Something Wrong!" message:[error localizedDescription] preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:mainAlert animated:YES completion:nil];
}];}
and to call it
[self setupConnectionWithsuccess:^(id responseObject, NSError *error) {
if (responseObject) {
NSLog(#"responsceObect");
}
}];
It get nothing while your function return. Because your block excute at asynchonize way. you should modify your function to handle the Array data in a block.
I am working on afnetworking, i have web service that takes too much time to load data and i want that UI do not freeze, i used this tutorial to run webservice on background so that i can work on other views as well, but not sucess till yet.
-(void) getArticles :(NSString*)stateAbbre completionHandler:(void (^)(id array))success
{
[MyCommonFunctions showGlobalProgressHUDWithTitle:#"Loading"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *link = [NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/depilexs/get_articles_ios.php"];
NSLog(#"%#",link);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager GET:link parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSDictionary *returnedDealDict = responseObject ;
NSArray *returnArray = [returnedDealDict objectForKey:#"Result"];
for(NSDictionary *dealDict in returnArray)
{
ArticlesDC *articles = [[ArticlesDC alloc] init];
articles.articlesID = [[dealDict objectForKey:#"id"]intValue ];
articles.articleTitle = [dealDict objectForKey:#"title" ];
articles.articleDetail = [dealDict objectForKey:#"details" ];
articles.articleDate = [dealDict objectForKey:#"date" ];
articles.articlePic = [dealDict objectForKey:#"pic" ];
articles.articleThumbPath = [dealDict objectForKey:#"thumb_path" ];
articles.articleStatus = [dealDict objectForKey:#"status" ];
[dataArray addObject:articles];
[MyCommonFunctions dismissGlobalHUD];
}
success(dataArray);
// [MBProgressHUD hideHUDForView:self.view animated:YES];
if (dataArray.count == 0)
{
ALERT_VIEW(#"Please check your internet connection.");
// [MBProgressHUD hideHUDForView:self.view animated:YES];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
ALERT_VIEW(#"Error occured while loading data.");
// [MBProgressHUD hideHUDForView:self.view animated:YES];
}];
}
and in my view did load method
[self getArticles:nil completionHandler:^(id array) {
articlesArray = array;
[tblView reloadData];
for (ArticlesDC *article in articlesArray)
{
NSString *stringWithoutSpace = [[NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/admin/%#", article.articleThumbPath] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString: stringWithoutSpace]];
UIImage *imgOne = [UIImage imageWithData:imageData];
NSString *stringforImg = [[NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/admin/%#", article.articlePic] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageDta = [NSData dataWithContentsOfURL:[NSURL URLWithString: stringforImg]];
UIImage *imgTwo = [UIImage imageWithData:imageDta];
[dbHandler insertArticlesIntoSqlite:article.articleTitle andDetail:article.articleDetail anddate:article.articleDate andImage:[MyCommonFunctions saveImageInDocuments:imgTwo] andThumb:[MyCommonFunctions saveImageInDocuments:imgOne]];
[defaults setInteger:1 forKey:#"getArticlesOffline"];
[defaults synchronize];
}
}];
The problem is not AF, it's that at the end of that process you call dataWithContentsOfURL twice and this runs directly on the main thread to download some images. You need to move that download to a background thread.
first I'd like to say that the issue I am having is in regards to how my own code is set, not IOS or AFNetworking.
I am going to show 1 example where a view is not refreshing immediately even though the updated JSON response object from the server is being recieved.
There are 2 views being used in the first view the button below takes the user to a second view where he can upload an image that will then be displayed in the first view.
- (IBAction)editImage:(id)sender {
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:#"Main_iPhone" bundle:nil];
TDUserProfileViewController * vc = [storyboard instantiateViewControllerWithIdentifier:#"TDUserProfileImageEditViewController"];
[self.navigationController pushViewController:vc animated:YES];
}
Below is the code that uploads the new data to the server and then gets new data regarding the images's address on the server.
- (IBAction)dataSubmitToServer{
// NSLog(#"photo: %#", self.photoData);
NSString * userID = [[NSUserDefaults standardUserDefaults] objectForKey:USERID];
//make the call to the web API
NSString* command = #"setProfilePhoto";
self.params =[NSMutableDictionary dictionaryWithObjectsAndKeys:command, #"command", userID, #"userid", nil];
//////////////////
NSLog(#"%#", self.params);
self.photoName = #"newname.png";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:BaseURLString parameters:self.params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(self.userPhoto.image, 1)
name:#"image"
fileName:self.photoName
mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
[TDPublicFunctions showDefaultAlert:#"Error" body:[error description]];
}];
[self getNewProfileData];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)getNewProfileData{
/*start getting new data for profile pic and status message*/
NSString* command = #"displayProfileData";
NSString * userID = [[NSUserDefaults standardUserDefaults] objectForKey:USERID];
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:command, #"command", userID,#"userid", nil];
NSLog( #"%#", params);
[SVProgressHUD showWithStatus:#"Loading..." maskType:SVProgressHUDMaskTypeBlack];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:BaseURLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
[SVProgressHUD dismiss];
if([responseObject objectForKey:#"error"])
{
[[[UIAlertView alloc] initWithTitle:#"Data Retrieval Error" message:[responseObject description] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil] show];
}
else
{
NSString * profilePhoto = [[[responseObject objectForKey:#"result"] objectAtIndex:0] objectForKey:#"profile_picture"];
NSString * status = [[[responseObject objectForKey:#"result"] objectAtIndex:0] objectForKey:#"status"];
NSString * statusMsg = [[[responseObject objectForKey:#"result"] objectAtIndex:0] objectForKey:#"status_message"];
if(profilePhoto && ![profilePhoto isKindOfClass:[NSNull class]])
[[NSUserDefaults standardUserDefaults] setObject:profilePhoto forKey:PROFILE_PHOTO];
if(status && ![status isKindOfClass:[NSNull class]])
[[NSUserDefaults standardUserDefaults] setObject:status forKey:STATUS];
if(statusMsg && ![statusMsg isKindOfClass:[NSNull class]])
[[NSUserDefaults standardUserDefaults] setObject:statusMsg forKey:STATUS_MESSAGE];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
//end of getting data for status message and profile pic
}
Now once this above process is over the HUD is supposed to stop and when the back button on the view is hit there should be a newly uploaded image in the first view. The code below is the last of many things that I have tried in order to get the view with the image to refresh:
-(void) viewWillAppear:(BOOL)animated
{
NSString * profPic = [[NSUserDefaults standardUserDefaults] objectForKey:PROFILE_PHOTO];
NSLog(#"profilepic: %#", profPic);
// NSString* status = [[NSUserDefaults standardUserDefaults] objectForKey:STATUS];
NSString * statusMsg = [[NSUserDefaults standardUserDefaults] objectForKey:STATUS_MESSAGE];
if(profPic)
[photo loadIconForProduct:profPic];
if(statusMsg)
statusMsgView.text = statusMsg;
//self.view=nil;
//[self viewDidLoad];
[self getFriendsList];
[photo setNeedsDisplay];
[self.view setNeedsDisplay];
}
After an image is uploaded it may work the first time an image is uploaded but it does not work if the user were to press the editImage button a second time and upload another image.
What is it that is being done wrong? Let me know if there is anything else that I can supply.
Thanks.
As I can see here, you are getting a URL back as the result of the profilePhoto. So you might as well use the AFNetworking function:
Im presuming photo is a UIImageView.
[photo setImageWithURL:[NSURL URLWithString:profPic] placeholderImage:[UIImage imageNamed:#"somePlaceholderImage"]];