block not being called on the other end - ios

i'm new to blocks, I have a class of requests with static methods to call me back on UIViewControllers with some blocks
this is the method implementation :
(putting a breakpoint on the block(something) DOES stop there, like it should)
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*callBackArray))block
{
if ([text isEqualToString:#""] || [text isEqualToString:#" "])
{
block(nil);
return;
}
NSString * key = #"someActualKeyHere";
;
NSString * finalText;
NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:text];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([language isEqualToString:#"he"])
{
finalText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
else
{
finalText = [text stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
NSString *urlString = [NSString stringWithFormat:
#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%#&types=geocode&sensor=true&key=%#",finalText,key];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (!responseObject && ![responseObject respondsToSelector:#selector(dataWithData:)])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving "
message:#"ERROR"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
return ;
}
NSData * responseData = [NSData dataWithData:responseObject];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSError *err;
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
} 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];
}
this is how I call it, notice the NSLog, i put a breakpoint on it and its never called
which is exactly what I want to occur.
[Requests requestSuggestedLocationsForText:text withBlock:^(NSArray *callBackArray)
{
NSLog(#"ROFL");
}];
for the record, I have tried the same method with a different signature (without the returning variable name like so :
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*))block;
still didn't fire my breakpoint :(

I think that this:
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
Never runs because as far as I know, NSString doesn't declare JSONObjectWithData. Your break point will never hit because it will never be called.
It seems like it could just be:
NSData * responseData = [NSData dataWithData:responseObject];
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (!err) {
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
else {
block(nil);
}
The other way you convert it to a string, then back to data, why not just keep it as data?

Related

Upload 5 images to server using AFNetworking [duplicate]

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];
}];
}

Forward geocoding doesnt give correct results

I didn't get correct results for Forward geocoding in certain cases. When I search for some places or hotel it shows result of some others places or areas. I have got following code. I study the following link. What url should i place to get correct results.
how can we implement the following given in following site
https://developers.google.com/places/webservice/autocomplete
A request for addresses containing "Vict" with results in French:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&key=API_KEY
A request for cities containing "Vict" with results in Brazilian
Portuguese:
https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=(cities)&language=pt_BR&key=API_KEY
I have implemented following but it doesn't give the results as i aspected
- (CLLocationCoordinate2D)addressLocation{
NSError *error = nil;
// NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", SearchtextField];
// NSString *API_KEY=#"AIzaSyB27SkGBzvEYKcxvZ5nmOVWvrA-6Xqf-7A";
NSString *API_KEY=#"AIzaSyCHcqJcqZbP1XpU-WB4VfRct5hpdgqisSY";
NSString *lookUpString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#&region=np&key=%#", SearchtextField,API_KEY];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
NSArray *locationArray = [[[jsonDict valueForKey:#"results"] valueForKey:#"geometry"] valueForKey:#"location"];
NSString *statusString = [jsonDict valueForKey:#"status"];
if ([statusString isEqualToString:#"OK"])
{
locationArray = [locationArray objectAtIndex:0];
Str_Latitude= [locationArray valueForKey:#"lat"];
Str_Longitude= [locationArray valueForKey:#"lng"];
NSLog(#"LatitudeString:%# & LongitudeString:%#", Str_Latitude, Str_Longitude);
/*Google place latitude Longitude*/
Arr_LatLong = #[Str_Latitude,Str_Longitude];
[[NSUserDefaults standardUserDefaults] setValue:Str_Latitude forKey:#"Str_Latitude"];
[[NSUserDefaults standardUserDefaults] setValue:Str_Longitude forKey:#"Str_Longitude"];
[[NSUserDefaults standardUserDefaults] synchronize];
GogLatitude = [Str_Latitude doubleValue];
Goglongitude = [Str_Longitude doubleValue];
if (Bool_SearchField) {
[self getGoogleAddress];
Bool_SearchField=FALSE;
}else{
}
}else{
UIAlertView *alertview =[[UIAlertView alloc] initWithTitle:#"Address not found" message:#"make sure you enter a valid address" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertview show];
NSLog(#"Something went wrong, couldn't find address");
[self.tableView reloadData];
}
GogLocation.latitude = GogLatitude;
GogLocation.longitude = Goglongitude;
return GogLocation;
}
When i search for radission in maps.google.com it shows as below
But when i search in my app it shows different locations then what I search
You can either take use of the Region Biasing, which according to wiki, should be NP. So add &region=np at the end of your query.
Or you can use the Viewport Biasing to set the bounds of your searches.
I have done what you have asked in one of my apps, but the url is different.
I am posting the function that gets called each time i input something in a text field.
-(void) startAutocomplete{
NSString* baseUrl = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%#&key=AIzaSyDz3HAmNY8NsgIhtA8gtbH-QA08Lg9tej4&types=all", self.locationTextfield.text];
NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"Url: %#", url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError!=nil) {
[[[UIAlertView alloc] initWithTitle:nil message:connectionError.localizedDescription delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] show ] ;
}else{
NSError *error = nil;
self.searchResult= [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//NSLog(#"result:%#",self.searchResult);
[self.tableView reloadData];
}
}];
}

How to parse JSON response from Rest API

I am working on an app that will parse data from a Rest API. As I haven't done this before, I was wondering if NSScanner or NSRange would work for this. Here is an example using NSScanner for such purposes. It's a small string so it doesn't take much code, so it seemed like a quick and dirty option. Is there an easier and quicker way to do this?
- (void)GetAliasName:(NSString *)cno selector:(NSString*)selectorName completionHandler:(void (^)(NSDictionary *, NSError *))handler
{
NSMutableDictionary *d = [[NSMutableDictionary alloc] init];
[d setValue:interface forKey:#"interface"];
[d setValue:#"GetAlias" forKey:#"method"];
NSMutableDictionary *p = [[NSMutableDictionary alloc] init];
cno = [[NSUserDefaults standardUserDefaults] objectForKey:#"cno"];
[p setValue:cno forKey:#"cno"];
[p setValue:selectorName forKey:#"selector"];
[d setValue:p forKey:#"parameters"];
NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
[self load:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"done");
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"GetAlias RAW response = %#", s);
if (apiConditions)
{
dispatch_async(dispatch_get_main_queue(),
^{
[hud hide:YES];
[MBProgressHUD hideHUDForView:self.view animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"No network connection or no data found" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
NSLog(#"data is NIL");
});
}
else
{
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
handler(d, error);
//scans for aliasname
NSString *match = #"AliasName\": \"";
NSString *preTel;
NSString *postTel;
NSScanner *scanner = [NSScanner scannerWithString:s];
[scanner scanUpToString:match intoString:&preTel];
[scanner scanString:match intoString:nil];
postTel = [s substringFromIndex:scanner.scanLocation];
//removes newlines, characters, and whitespaces from aliasname
NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:#"}]\""];
postTel = [[postTel componentsSeparatedByCharactersInSet: trim] componentsJoinedByString: #""];
postTel = [[postTel componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString: #""];
NSLog(#"postTel: %#", postTel);
NSString *docno = [[NSUserDefaults standardUserDefaults] objectForKey:#"docno"];
//if docno is filled in, look up TR by docno
if ([docno isEqual: #""])
{
[self GetTR:(NSString*)postTel customStatus:customStatus completionhandler:^(NSDictionary *dictionary, NSError *error) {
nil;
}];
}
}];
}
There is NSJSONSerialization which is built for this.
Use it as follows:
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSString *aliasName = dictionary[#"AliasName"];
Edit
Since you already use this, and have dictionary, the only step you needed was to access dictionary with needed key(last step).

Uploading NSData image via POST in iOS

i have a form that contains some person information and an image. i tried to save information in post using this function and it work well :
- (void)Inscription:(NSArray *)value completion:(void (^)( NSString * retour))block{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSArray *Param_header = #[#"username", #"password", #"email",#"first_name", #"last_name",#"image"];
// NSArray *Param_value = #[#"ali", #"aliiiiiiii", #"ali.ali#gmail.com",#"ali",#"zzzzz"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: [NSString stringWithFormat:#"http:// /Messenger/services/messenger_register"]]];
NSString *aa=[self buildParameterWithPostType:#"User" andParameterHeaders:Param_header ansParameterValues:value];
[request setHTTPBody:[aa dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
NSError *error = Nil;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
block([NSString stringWithFormat:#"%#", [jsonObjects objectForKey:#"message"]]);
}
}
];
}
No, i want to send the photo taked, i convert it to NSData first :
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *imag= [info objectForKey:#"UIImagePickerControllerOriginalImage"];
imag = [imag scaleAndRotateImage:imag];
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 25*1024;//was 250x1024
NSData *imageData = UIImageJPEGRepresentation(imag, compression);
while ([imageData length] > maxFileSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(imag, compression);
}
NSData _D_ImageData = imageData;
And i tried to do this to send it to server but image c'ant be uploaded:
[web Inscription:Param_value completion:^(NSString *retour) {
CustomPrpgress.hidden=true;
NSLog(#" eee %# ",retour);
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:retour message:#"" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}];
Can someone help me, i'm beginner and this is my first time. thank you
My code work fine, i made a mistake in the php file

Unable to search in iTunes Store on iOS8

I'm using this code to open iTunes Store app and search for specific music:
NSString *iTunesLink = [NSString stringWithFormat:#"http://search.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?entity=album&media=all&page=1&restrict=true&startIndex=0&term=TERM_NAME"];
NSURL *url = [NSURL URLWithString:iTunesLink];
[[UIApplication sharedApplication] openURL:url];
Code works fine on iOS7, by changing TERM_NAME value I can search whatever I want. The issue on iOS8 is that somehow search term is appended and prepended by ( " ) symbols. I'm using log to check what's the value of my NSURL but it looks fine.
This code worked for me:
NSString *artist = #"artist";
NSString *title = #"title";
NSOperationQueue *operationQueue = [NSOperationQueue new];
NSString *baseURLString = #"https://itunes.apple.com/search";
NSString *searchTerm = [NSString stringWithFormat:#"%# %#", artist, title];
NSString *searchUrlString = [NSString stringWithFormat:#"%#?media=music&entity=song&term=%#&artistTerm=%#&songTerm=%#", baseURLString, searchTerm, artist, title];
searchUrlString = [searchUrlString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
searchUrlString = [searchUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *searchUrl = [NSURL URLWithString:searchUrlString];
NSURLRequest *request = [NSURLRequest requestWithURL:searchUrl];
[NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse* response, NSData* data, NSError* error)
{
if (error)
{
NSLog(#"Error: %#", error);
}
else
{
NSError *jsonError = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError)
{
NSLog(#"JSON Error: %#", jsonError);
}
else
{
NSArray *resultsArray = dict[#"results"];
if(resultsArray.count == 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"917xfm" message:[NSString stringWithFormat:#"No results returned."] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
});
}
else
{
NSDictionary *trackDict = resultsArray[0];
NSString *trackViewUrlString = trackDict[#"trackViewUrl"];
if (trackViewUrlString.length)
{
NSURL *trackViewUrl = [NSURL URLWithString:trackViewUrlString];
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] openURL:trackViewUrl];
});
}
}
}
}
}];

Resources