Objective C Loading Icon on Timer - ios

I have created a loading icon for my application. While the application is loading the map and placing the markers I have a loading icon displaying on the screen rotating. With my current code the loading icon shows, but only rotates when the markers are all placed on the map and everything is finished loading. I have tried about everything, can anyone help?
I will attach code below, I do understand this is not the best way to do it and I plan to neaten it up once I find out what I am doing wrong getting it to rotate when the map is loading.
Thanks.
- (void)viewDidLoad
{
[super viewDidLoad];
loading=#"0";
rotateTimer = [NSTimer scheduledTimerWithTimeInterval:0.3
target:self
selector:#selector(rotateMove)
userInfo:nil
repeats:YES];
}
-(void)rotateMove
{
if([loading isEqual:#"1"])
{
[rotateTimer invalidate];
rotateTimer = nil;
}
if([loading isEqual:#"0"])
{
NSLog(#"move");
[UIView animateWithDuration:1.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
[self.rotate setTransform:CGAffineTransformRotate(self.rotate.transform, M_PI_2)];
} completion:^(BOOL finished){
if (finished) {
}
}];
}
}
EDITED: ADDED MAP CODE BELOW
-(void)mapload
{
[self.mapView clear];
NSString *lat = [[NSString alloc] initWithFormat:#"%g", latitude];
NSString *lng = [[NSString alloc] initWithFormat:#"%g", longitude];
NSURL *blogURL =
NSLog(#"URL = %#", blogURL);
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
if(jsonData == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Error" message:#"Please check your internet connection and try again." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
return;
}
else{
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSArray *test = [dataDictionary objectForKey:#"test"];
self.bottombutton.hidden=FALSE;
self.time.hidden=FALSE;
self.mins.hidden=FALSE;
self.rotate.hidden=TRUE;
int tes = [[test[0] valueForKey:#"time"] intValue];
}
for (int i = 0; i < [test count]; i++) {
for(NSDictionary *coordinates in test){
double la=[coordinates[#"lat"] doubleValue];
double lo=[coordinates[#"long"] doubleValue];
CLLocation * loca=[[CLLocation alloc]initWithLatitude:la longitude:lo];
CLLocationCoordinate2D coordi=loca.coordinate;
GMSMarker *marker= [[GMSMarker alloc] init];
marker=[GMSMarker markerWithPosition:coordi];
marker.snippet = coordinates[#"name"];
marker.map = self.mapView;
marker.appearAnimation = kGMSMarkerAnimationPop;
UIImage * image = [UIImage imageNamed:#"mapiconlarge"];
CGSize sacleSize = CGSizeMake(45, 45);
UIGraphicsBeginImageContextWithOptions(sacleSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, sacleSize.width, sacleSize.height)];
UIImage * resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSLog(#"markeradded");
marker.icon = resizedImage;
NSLog(loading);
}
}
}
}

We need to tease apart the part of your code that should be done in the background -- at the very least, the network request -- and the code that must be done on the main -- anything that changes the UI...
// here, everything you do to prepare for the network request
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// make the network request
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
dispatch_async(dispatch_get_main_queue(), ^{
// here everything you do after with the json data result
});
});
So you don't drive yourself crazy with syntax, build two methods, the first one produces blogURL for use on the network request, the second, takes the NSData result and does everything else. This way, there's just a one-liner method invocation nested in that inner dispatch.

Related

How to get the current String Value from array in objective C

I am new in iOS and I am facing problem regarding to get current value of string from array.
My code is like this
loginStatusHS = [[NSString alloc] initWithBytes: [myNSMDatalatetudeFromServer mutableBytes] length:[myNSMDatalatetudeFromServer length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusHS);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusHS error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultHS = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultHS);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"HS_GetResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"HS_GetResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responseletetudedict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"Latetude Dictionary =%#",responseletetudedict);
idlatetudearray=[[NSMutableArray alloc]init];
idlatetudearray=[responseletetudedict valueForKey:#"City"];
NameHSArray=[[NSMutableArray alloc] init];
NameHSArray=[responseletetudedict valueForKey:#"Name"];
AddressHSArray=[[NSMutableArray alloc] init];
AddressHSArray=[responseletetudedict valueForKey:#"Address"];
FacilitiesHSArray=[[NSMutableArray alloc] init];
FacilitiesHSArray=[responseletetudedict valueForKey:#"Facilities"];
PhoneNoHSArray=[[NSMutableArray alloc] init];
PhoneNoHSArray=[responseletetudedict valueForKey:#"Phoneno"];
FaxnoHSArray=[[NSMutableArray alloc] init];
FaxnoHSArray=[responseletetudedict valueForKey:#"Faxno"];
LatitudeHSArray=[[NSMutableArray alloc] init];
LatitudeHSArray=[responseletetudedict valueForKey:#"Latitude"];
LongitudeHSArray=[[NSMutableArray alloc] init];
LongitudeHSArray=[responseletetudedict valueForKey:#"Longitude"];
TypeHSArray=[[NSMutableArray alloc] init];
TypeHSArray=[responseletetudedict valueForKey:#"Type"];
for (int i=0; i<NameHSArray.count; i++) {
double LatitudeDouble = [LatitudeHSArray[i] doubleValue];
double LongitudeDouble = [LongitudeHSArray[i] doubleValue];
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(LatitudeDouble, LongitudeDouble);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
marker.title = NameHSArray[i];
marker.snippet=AddressHSArray[i];
userData = [[NSArray alloc] initWithObjects:NameHSArray[i], AddressHSArray[i],FacilitiesHSArray[i], PhoneNoHSArray[i],FaxnoHSArray[i], TypeHSArray[i], nil];
marker.userData = userData;
if([TypeHSArray[i] isEqualToString:#"ESIC"])
{
marker.icon = [UIImage imageNamed:#"mapicon2.png"];
}
else
{
marker.icon = [UIImage imageNamed:#"mapicon1.png"];
}
GMSCameraUpdate *zoomCamera = [GMSCameraUpdate zoomIn];
[mapView animateWithCameraUpdate:zoomCamera];
marker.map = mapView;
}
Add in the Image when I click on Nobel Hospital I call the delegate
- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
// your click action
StringAddress = marker.snippet;
StringName = marker.title;
NSLog(#"Address=%#",StringAddress);
NSLog(#"Name= %#",StringName);
lblNamepopup.text=StringName;
lblAddresspopup.text=StringAddress;
NSLog(#"User Data Array = %#",userData);
viewpopup.hidden=NO;
viewpopup.transform = CGAffineTransformMakeScale(0.01, 0.01);
[UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
viewpopup.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished){
// do something once the animation finishes, put it here
}];
}
Hear in this delegate I need to get the current name of string address.But hear I am getting the Last value means the string get override. How can I get the value which I have click from array. Thanks in Advance!
You can get index as follow
-(void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker
{
NSInteger index = [NameHSArray indexOfObject:marker.title];
NSLog(#"%ld",(long)index);
}
--- EDIT ---
You can also use
i found some reference from library.
Note that userData should not hold any strong references to any Maps
objects, otherwise a loop may be created (preventing ARC from releasing
objects).
NOTE :-
You can pass data through snippet but snippet show data into info window. so you creates a custom info window and show data as you want.
like this,
NSArray * userData = [NSArray alloc] initWithObjects:FacilitiesHSArray[i], PhoneNoHSArray[i],FaxnoHSArray[i], nil];
NSString *userDataString = [userData componentsJoinedByString:#";"];
marker.snippet = userDataString;
retrive
like this,
NSString *userDataString = marker.snippet;
NSArray *array = [userDataString componentsSeparatedByString:#";"];
NSLog(#"%#",array);
You can Do Like this
- (void)mapView:(GMSMapView *)mapView didTapInfoWindowOfMarker:(GMSMarker *)marker {
// your click action
StringAddress = marker.snippet;
StringName = marker.title;
NSInteger indexCheck = [NameHSArray indexOfObject:marker.title];
NSLog(#"Curret Index =%ld",(long)indexCheck);
StringName=[NSString stringWithFormat:#"%#",[NameHSArray objectAtIndex:indexCheck]];
StringAddress=[NSString stringWithFormat:#"%#",[AddressHSArray objectAtIndex:indexCheck]];
StringPhoneNo=[NSString stringWithFormat:#"%#",[PhoneNoHSArray objectAtIndex:indexCheck]];
NSLog(#"Address=%#",StringAddress);
NSLog(#"Name= %#",StringName);
NSLog(#"Phone No =%#",StringPhoneNo);
lblNamepopup.text=StringName;
lblAddresspopup.text=StringAddress;
}

How to add Multiple custom marker on google maps and how to change custom marker when it taped and untaped

I want to show multiple number of markers on goolemaps which is of different colours say red, green ,orange ,black marker shown in the below image.I have to show the price in the marker when I select some marker then Marker image must change same like the below image
I am getting lat and long of marker from web services and using that data I am add markers,text in the marker using the below code but the Image is becoming blur .
-(void)hourelywebsevice:(NSString *)withlogintoken withlat:(double )weblat withlong:(double )weblong withcoustamerid:(NSString *)coustamerid{
NSLog(#"%#",withlogintoken);
NSLog(#"%f",weblat);
NSString *weblatstring=[NSString stringWithFormat:#"%f",weblat];
NSString *weblongstring=[NSString stringWithFormat:#"%f",weblong];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:weblatstring,#"lat",weblongstring,#"lon",coustamerid,#"customer_id",hourlyWebFromDateStr,#"fromtime",hourlyWebToDateStr,#"totime",withlogintoken,#"login_token",filtervechtypestr,#"vehicle_type",filteraminitesarray,#"amenities",filtertypearray,#"type", nil];
NSLog(#"%#",dict);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[manager POST:#"http://park24x7.com/betav2/apipoint/gethourlyserviceproviders" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
userarray=[responseObject objectForKey:#"data"];
statusstring=[NSString stringWithFormat:#"%#", [responseObject objectForKey:#"status"]];
NSInteger number=1;
NSInteger statustwonumber=2;
integerAsString = [NSString stringWithFormat:#"%ld",(long)number];
useridstring1=[NSString stringWithFormat:#"%#", [userarray valueForKey:#"id"]];
NSString *satustwostring= [NSString stringWithFormat:#"%ld",(long)number];
alertstring =[responseObject objectForKey:#"message"];
if([statusstring isEqualToString:integerAsString])
{
NSLog(#"%#",alertstring);
//
if (!(alertstring.length==0 )) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:alertstring
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[activityIndicatorView stopAnimating];
[alert show];
}else{
vehicle_id=[NSString stringWithFormat:#"%#", [responseObject objectForKey:#"vehicle_id"]];
Carnumber_string=[NSString stringWithFormat:#"%#", [responseObject objectForKey:#"vehicle_number"]];
int i;
for (i=0; i<userarray.count; i++)
{
marker1 = [[GMSMarker alloc] init];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,60,60)];
NSString *space_remaingcountstring=[[userarray objectAtIndex:i ]valueForKey:#"space_remain"];
NSInteger space_remaingcountInt=[space_remaingcountstring integerValue];
UIImageView *pinImageView;
int spacesAvilable,spacesOccupied,spacesRemain;
NSString *spacesAvilableStr,*spacesOccupiedStr,*spacesRemainStr;
spacesAvilableStr=[[userarray objectAtIndex:i ]valueForKey:#"space_available"];
;
spacesOccupiedStr=[[userarray objectAtIndex:i ]valueForKey:#"space_occupied"];
spacesRemainStr=[[userarray objectAtIndex:i ]valueForKey:#"space_remain"];
spacesAvilable=[spacesAvilableStr intValue];
spacesOccupied=[spacesOccupiedStr intValue];
spacesRemain=[spacesRemainStr intValue];
float precentage = 100*spacesOccupied/spacesAvilable;
NSLog(#" precentage %f",precentage);
if (spacesAvilable<=2) {
pinImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"marker-orange-48"]];
}
else
{
if (precentage<=50) {
pinImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"marker-green-48"]];
}else if (precentage>50)
{
pinImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"marker-black-48"]];
}
}
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(12, 7, 30, 20)];
NSString *pricestring=[[userarray objectAtIndex:i ]valueForKey:#"hourly_price"];
label.text=pricestring;
label.textColor=[UIColor colorWithRed:187/255.0 green:0/255.0 blue:29/255.0 alpha:1];
label.font=[UIFont systemFontOfSize:9.0f];
[view addSubview:pinImageView];
[pinImageView addSubview:label];
UIImage *markerIcon = [self imageFromView:view];
marker1.icon = markerIcon;
NSString *resultdictlatstring=[[userarray objectAtIndex:i ]valueForKey:#"loc_lat"];
float resultdictlatfloat=[resultdictlatstring floatValue];
NSLog(#"%f",resultdictlatfloat);
NSString *resultdictlongstring=[[userarray objectAtIndex:i ]valueForKey:#"loc_long"];
float resultdictlongfloat=[resultdictlongstring floatValue];
NSLog(#"%f",resultdictlongfloat);
marker1.position = CLLocationCoordinate2DMake(resultdictlatfloat, resultdictlongfloat);
NSLog(#"%f",marker1.position);
marker1.appearAnimation = kGMSMarkerAnimationPop;
marker1.map = hrlymapView;
marker1.zIndex=i;
NSLog(#"%d",marker1.zIndex);
}
[activityView stopAnimating];
}
}
else if ([statusstring isEqualToString:satustwostring]){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:alertstring
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[activityIndicatorView stopAnimating];
[alert show];
[activityView stopAnimating];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:alertstring
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[activityIndicatorView stopAnimating];
[alert show];
[hrlymapView clear];
[activityView stopAnimating];
}
}
failure:^(NSURLSessionTask* operation, NSError* error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry!!"
message:#"The Internet connection appears to be offline"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[activityIndicatorView stopAnimating];
[alert show];
[activityView stopAnimating];
[hrlymapView clear];
NSLog(#"Error: %#", error);
}];
}
- (UIImage *)imageFromView:(UIView *) view
{
UIGraphicsBeginImageContext(view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[view.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
// if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) {
// UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [[UIScreen mainScreen] scale]);
// } else {
// UIGraphicsBeginImageContext(view.frame.size);
// }
// [view.layer renderInContext: UIGraphicsGetCurrentContext()];
// UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
// return image;
}
In didtap marker I am add belowcode to get the data from the marker I change the image of marker but I it not working
- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)tappedMarker
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
_hourlyparkingSpotDetailsView.hidden=NO;
_hourlyTapOnMarkerLblView.hidden=YES;
_monthlyParkingSpotDetailsView.hidden=NO;
_currentLocationBtn.frame=CGRectMake(_currentLocationBtn.frame.origin.x, _hourlyparkingSpotDetailsView.frame.origin.y-80, _currentLocationBtn.frame.size.width, _currentLocationBtn.frame.size.height);
//marker.map=nil;
NSLog(#"You tapped at %f,%f", tappedMarker.position.latitude,tappedMarker.position.longitude);
destinationlat_fvalue=tappedMarker.position.latitude;
destinationlon_fvalue=tappedMarker.position.longitude;
tappedMarker.icon=[UIImage imageNamed:#"pin-selected"];
NSLog(#"%d",tappedMarker.zIndex);
_hourlyparkingSpotDetailsView.hidden=NO;
_hourlyTapOnMarkerLblView.hidden=YES;
_monthlyParkingSpotDetailsView.hidden=YES;
_hourlyparkingSpotAddressLbl.text=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"address"];
_hourlyParkingSpotPriceLbl.text=[NSString stringWithFormat:#"%#/h",[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"hourly_price"]];
_markerSpaceIdStr=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"space_id"];
_hourlyParkingSpotZoneId=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"zone_id"];
_hourlyParkingSptVehicleType=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"vehicle_type"];
_hourlyreviews=[NSString stringWithFormat:#"%# Reviews", [[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"reviws"]] ;
_hourlyspacetype=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"space_type"];
NSString *currency_symbol=[NSString stringWithFormat:#"%#", [[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"currency_symbol"]];
_hourlyRupeeSymbolLbl.text=currency_symbol;
[defaults setObject:currency_symbol forKey:#"currency_symbol"];
_hourlyAutomatedLbl.text=_hourlyspacetype;
_hourlyReviewsLbl.text=_hourlyreviews;
if(isMarkerActive == TRUE){
[self unhighlightMarker:marker1];
}
isMarkerActive = TRUE;
selectedMarker = tappedMarker;
[self highlightMarker:tappedMarker];
return YES;
}
-(void)highlightMarker:(GMSMarker *)tappedMarker{
if([hrlymapView.selectedMarker isEqual:tappedMarker]){
tappedMarker.icon = [UIImage imageNamed:#"pin-selected"];
}
}
-(void)unhighlightMarker:(GMSMarker* )UntappedMarker{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,70,70)];
UIImageView *pinImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pin-red-2"]];
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(23, 15, 29, 23)];
NSString *pricestring=[[userarray objectAtIndex:UntappedMarker.zIndex ]valueForKey:#"hourly_price"];
label.text=pricestring;
label.textColor=[UIColor colorWithRed:187/255.0 green:0/255.0 blue:29/255.0 alpha:1];
label.font=[UIFont systemFontOfSize:11.0f];
[view addSubview:pinImageView];
[pinImageView addSubview:label];
UIImage *markerIcon = [self imageFromView:view];
UntappedMarker.icon = markerIcon;
}
Thanks for quick answer,If you have any doubts in the code please let me know.
This is how add marker to map:
// set `SOME_NAME` on your logic
UIImage * markerIconImage = [UIImage imageNamed:SOME_NAME];
//lat - CGFloat value
//lng - CGFloat value
CLLocation * location = [[CLLocation alloc] initWithLatitude:lat longitude:lng];
GMSMarker * marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
marker.icon = markerIconImage;
marker.map = mapView; // mapView - is your map view
To not duplicate the answers, here is how to manipulate on marker select and deselect actions: [Change Google Maps' Selected Marker or change marker's color? [iOS] - the logic will be same.
While making marker object, you can give an id to each marker. that later can be used for identifying the same. I thing maker has a userInfo dictionary that can be used for this purpose
Example
GMSMarker *marker = [[GMSMarker alloc] init];
marker.userData = #{#"marker_id":[NSNumber numberWithInt:1]};
In delegate methods, you can get the marker id from userData.
NSNumber *number = [marker.userData objectForKey:#"marker_id"];

MBProgressHUD not updating progress

I am importing multiple photos from photos library and I want to show the progress using MBProgressHUD. I am using QBImagePickerController to import photos. My photos are imported successfully. However the progress bar in MBProgressHUD is not updating. The following is my code
-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets {
if (imagePickerController.filterType == QBImagePickerControllerFilterTypePhotos) {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];]
// Set the determinate mode to show task progress.
hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
hud.delegate = self;
hud.labelText = NSLocalizedString(#"Importing Photos", nil);
hud.dimBackground = YES;
hud.detailsLabelFont = [UIFont systemFontOfSize:12.0f];
hud.detailsLabelText = NSLocalizedString(#"Please wait...", nil);
hud.progress = 0.0f;
[self importPhotosForArray:assets];
}
[self dismissImagePickerController];
}
- (void) importPhotosForArray:(NSArray *)info {
for (ALAsset *selectedImageAsset in info) {
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary assetForURL:[selectedImageAsset defaultRepresentation].url resultBlock: ^(ALAsset *asset){
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
if (imageRef) {
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
// Create a file name for the image
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *imageName = [NSString stringWithFormat:#"photo-%#.png", [dateFormatter stringFromDate:[NSDate date]]];
// Now we get the full path to the file
NSString *fullPathToFile = [self.folder.fullPath stringByAppendingPathComponent:imageName];
// Write out the data.
[imageData writeToFile:fullPathToFile atomically:NO];
sleep(1.0);
progress = ++index/[info count];
[MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
if (progress >= 1.0) {
[[MBProgressHUD HUDForView:self.navigationController.view] hide:YES];
[self reloadData];
}
}
} failureBlock: ^(NSError *error){
// Handle failure.
NSLog(#"Failure");
}];
}
}
declare MBProgressHUD As property and use it every where.
#property (nonatomic, strong) MBProgressHUD *hud;
-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets {
if (imagePickerController.filterType == QBImagePickerControllerFilterTypePhotos) {
self.hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];]
// Set the determinate mode to show task progress.
self.hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
self.hud.delegate = self;
self.hud.labelText = NSLocalizedString(#"Importing Photos", nil);
self.hud.dimBackground = YES;
self.hud.detailsLabelFont = [UIFont systemFontOfSize:12.0f];
self.hud.detailsLabelText = NSLocalizedString(#"Please wait...", nil);
self.hud.progress = 0.0f;
[self importPhotosForArray:assets];
}
[self dismissImagePickerController];
}
- (void) importPhotosForArray:(NSArray *)info {
for (ALAsset *selectedImageAsset in info) {
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary assetForURL:[selectedImageAsset defaultRepresentation].url resultBlock: ^(ALAsset *asset){
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
if (imageRef) {
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
// Create a file name for the image
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *imageName = [NSString stringWithFormat:#"photo-%#.png", [dateFormatter stringFromDate:[NSDate date]]];
// Now we get the full path to the file
NSString *fullPathToFile = [self.folder.fullPath stringByAppendingPathComponent:imageName];
// Write out the data.
[imageData writeToFile:fullPathToFile atomically:NO];
sleep(1.0);
progress = ++index/[info count];
self.hud.progress = progress;
if (progress >= 1.0) {
[MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
[self reloadData];
}
}
} failureBlock: ^(NSError *error){
// Handle failure.
NSLog(#"Failure");
}];
}
}
Try this
Because as per your code when u update progress every time new object of MBProgressHUD get and update
UI updates (i.e. changes to the progress bar) must be made on the main thread or you may suffer from unpredictable side effects.
The user interface element may not be redrawn after your property changes
I believe that ALAssetsLibrary.assetForURL is automatically happening in a background thread. To get around that you want to use a solution that lets you run the UI updates on the main thread. In this case your UI updates would be this line
[MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
so try something like this:
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
});
Also, you should verify that ++index/[info count] is actually increasing as you expect it to by printing the value out each time index updates.
Try this code. Replace your importPhotosForArray method with the following.
- (void) importPhotosForArray:(NSArray *)info {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
__block float progress = 0.0f;
__block float index = 0.0f;
for (ALAsset *selectedImageAsset in info) {
ALAssetRepresentation *representation = [selectedImageAsset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
if (imageRef) {
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *imageData = UIImagePNGRepresentation(image);
// Create a file name for the image
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *imageName = [NSString stringWithFormat:#"photo-%#.png", [dateFormatter stringFromDate:[NSDate date]]];
// Now we get the full path to the file
NSString *fullPathToFile = [self.folder.fullPath stringByAppendingPathComponent:imageName];
// Write out the data.
[imageData writeToFile:fullPathToFile atomically:YES];
sleep(1);
progress = ++index/[info count];
dispatch_async(dispatch_get_main_queue(), ^{
// Instead we could have also passed a reference to the HUD
// to the HUD to myProgressTask as a method parameter.
[MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
});
if (progress >= 1.0) {
dispatch_async(dispatch_get_main_queue(), ^{
// Instead we could have also passed a reference to the HUD
// to the HUD to myProgressTask as a method parameter.
[[MBProgressHUD HUDForView:self.navigationController.view] hide:YES];
[self reloadData];
});
}
}
}
});
}

network activity indicator not appearing in iOS app

In my iOS app, I want to show the network activity indicator in the top status bar.
I've added the following:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
But the activity indicator never appears.
Does anyone know what might be wrong?
Here is the full code:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
// load sets
[self loadSets];
}
-(void)loadSets{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"in loadSets");
// show loading animation
UIView *loadingView = loadingIndicator;
loadingView.center = CGPointMake(screenWidth/2, screenHeight/2);
[self.view addSubview:loadingView];
[loadingIndicator startAnimating];
self.userSets = [[NSMutableArray alloc]init]; // re-initialize userSets
dispatch_async(bgQueue, ^{
NSString *userURLString = [userBaseUrl stringByAppendingFormat:#"/%#.json?auth_token=%#", username, auth_token];
NSLog(#"userURLString %#", userURLString);
NSURL *userURL = [NSURL URLWithString:userURLString];
NSData * userData = [NSData dataWithContentsOfURL:userURL];
dispatch_async(dispatch_get_main_queue(), ^{
if(userData){
[self fetchSets:userData];
// remove loading animation
[loadingView removeFromSuperview];
}else{
// error with authentication - should log out and require relogin
// [self logoutClick];
}
});
});
});
}
-(void)fetchSets:(NSData *)responseData{
NSError * error;
NSDictionary * json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if(json){
NSArray *sets = [json objectForKey:#"sets"];
for (NSDictionary *currentSet in sets){
Set *userSet = [[Set alloc] init];
userSet.name = [currentSet objectForKey:#"name"];
userSet.videoURL = [[currentSet objectForKey:#"media"] objectForKey:#"mp4"];
userSet.gifURL = [[currentSet objectForKey:#"media"] objectForKey:#"gif"];
userSet.imgURL = [[currentSet objectForKeyedSubscript:#"media"] objectForKey:#"img"];
userSet.setID = [currentSet objectForKey:#"id"];
[self.userSets addObject: userSet];
}
NSLog(#"trying to reload table data with userSets length %d", [self.userSets count]);
[self.collectionView reloadData];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"done loading table data");
});
}
}

GoogleMaps iOS SDK Version 1.5 unresponsive

I am using the latest GoogleMaps iOS SDK in my application and after the latest iOS update, 7.0.3, it started becoming unresponsive after first touch. Let me expand on this. After the first touch on the map, the map becomes unresponsive. At first, you can pinch zoom, drag, swipe, and everything else but after that first touch, it no longer works. This started happening after Apple updated their iOS. If I use the iOS6 simulator, I can can do all the gestures even after the first touch. I don't know if this is because of the iOS update or something is wrong with my code. If anyone has any suggestions or has gone through something like this that could guide me, that could be greatly appreciated. Thanks in advance.
Followed the website instructions here: (https://developers.google.com/maps/documentation/ios/start#adding_the_google_maps_sdk_for_ios_to_your_project)
and it works on iOS6 and was working on iOS7 before.
MapsViewController.m
#import "MapsViewController.h"
#import <GoogleMaps/GoogleMaps.h>
#interface MapsViewController ()
#end
#implementation MapsViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.storeNamesArray = [[NSMutableArray alloc] init];
self.storePricesArray = [[NSMutableArray alloc] init];
self.storeLatitudeArray = [[NSMutableArray alloc] init];
self.storeLongitudeArray = [[NSMutableArray alloc] init];
self.priceTypeArray = [[NSMutableArray alloc] init];
dispatch_async(dispatch_get_main_queue(), ^{ NSData *data =
[NSData dataWithContentsOfURL:[NSURL URLWithString:
[NSString stringWithFormat: #"http://www.someurl.com/mobile-api"]]];
[self performSelectorOnMainThread:#selector(fetchData:) withObject:data
waitUntilDone:YES]; });
}
-(void)fetchData:(NSData *)responseData
{
if (responseData)
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *stores =[json objectForKey:#"stores"];
for(NSDictionary *location in stores)
{
[self.storeNamesArray addObject:[location objectForKey:#"name"]];
[self.storePricesArray addObject:[location objectForKey:#"price"]];
[self.storeLatitudeArray addObject:[location objectForKey:#"latitude"]];
[self.storeLongitudeArray addObject:[location objectForKey:#"longitude"]];
[self.priceTypeArray addObject:[location objectForKey:#"price_type"]];
}
}
double lat = 0.0;
double lon = 0.0;
GMSCameraPosition *camera;
if(self.currentLocationArray.count !=0)
{
lat = [self.currentLocationArray[0] doubleValue];
lon = [self.currentLocationArray[1] doubleValue];
camera = [GMSCameraPosition cameraWithLatitude:lat longitude:lon zoom:12];
}
else
{
lat = [self.storeLatitudeArray[0] doubleValue];
lon = [self.storeLongitudeArray[0] doubleValue];
camera = [GMSCameraPosition cameraWithLatitude:lat longitude:lon zoom:9];
}
GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
for(int i=0; i<self.storeNamesArray.count; i++)
{
GMSMarker *marker = [[GMSMarker alloc] init];
marker.title = self.storeNamesArray[i];
marker.snippet = [NSString stringWithFormat:#"%# $%#", self.priceTypeArray[i], self.storePricesArray[i]];
marker.position = CLLocationCoordinate2DMake([self.storeLatitudeArray[i] doubleValue], [self.storeLongitudeArray[i] doubleValue]);
marker.map = mapView;
}
if(self.currentLocationArray.count !=0)
{
GMSMarker *currentMarker = [[GMSMarker alloc] init];
currentMarker.title = #"Current Location";
currentMarker.snippet = #"You are here";
currentMarker.position = CLLocationCoordinate2DMake(lat, lon);
currentMarker.map = mapView;
currentMarker.icon = [UIImage imageNamed:#"temp_userLocation"];
mapView.selectedMarker = currentMarker;
}
CGRect newFrame = self.view.bounds;
newFrame.size.height = frame.size.height / 2;
mapView.frame = newFrame;
mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
mapView.delegate = self;
[self.view addSubview:mapView];
}
I've published my reworked version of Chris's code on the Google Maps SDK for iOS bug.
The solution involved two changes to Chris's code:
Migrate the Google Map instantiation to viewDidLoad,
Push the network traffic from the Main (UI) thread to a background thread.
I don't know if that's the case here but I had same issue with URLWithString function appears only on iOS 7.0.3, I assume Apple has change the characters this function can use so if it returns nil this is your solution.
What I did is using this function to create the string before using it with URLWithString:
-(NSString *) URLEncodeString:(NSString *) str // New to fix 7.0.3 issue //
{
NSMutableString *tempStr = [NSMutableString stringWithString:str];
[tempStr replaceOccurrencesOfString:#" " withString:#"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
return [[NSString stringWithFormat:#"%#",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
On your case just change the line to this one:
dispatch_async(dispatch_get_main_queue(), ^{ NSData *data =
[NSData dataWithContentsOfURL:[NSURL URLWithString:[self URLEncodeString: [NSString stringWithFormat: #"http://www.someurl.com/mobile-api"]]]];
[self performSelectorOnMainThread:#selector(fetchData:) withObject:data
waitUntilDone:YES]; });
Hope that would help you too.
insert this code in viewDidLoad method
-(void)viewDidLoad
{
[super viewDidLoad];
// iOS7
if ([self.navigationController respondsToSelector:#selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
.... your codes
}

Resources