How do I send an array of integers via GKSession bluetooth - ios
I have a problem with sending an array of integers via GKSession.
This is how I did it:
To send it.
-(void)sendData {
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject:[NSNumber numberWithInteger:snakeHead.position.x]];
[myArray addObject:[NSNumber numberWithInteger:snakeHead.position.y]];
[myArray addObject:[NSNumber numberWithInteger:direction.x]];
[myArray addObject:[NSNumber numberWithInteger:direction.y]];
[myArray addObject:[NSNumber numberWithInteger:bodyOffsetX]];
[myArray addObject:[NSNumber numberWithInteger:bodyOffsetY]];
[myArray addObject:[NSNumber numberWithInteger:amountBodies]];
NSData* encodedArray = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[snakeSession sendData:encodedArray toPeers:snakePeers withDataMode:GKSendDataReliable
error:nil];
[encodedArray release];
}
The sendData function is called from a scheduler.
To receive it.
-(void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session
context:(void *)context {
NSArray *hisArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
snakeHead2.position = ccp([[hisArray objectAtIndex:0] integerValue],
[[hisArray objectAtIndex:1] integerValue]);
direction2 = ccp([[hisArray objectAtIndex:2] integerValue],
[[hisArray objectAtIndex:3] integerValue]);
bodyOffsetX2 = [[hisArray objectAtIndex:4] integerValue];
bodyOffsetY2 = [[hisArray objectAtIndex:5] integerValue];
amountBodies2 = [[hisArray objectAtIndex:6] integerValue];
}
This does not work and the game crashes.
So what am I doing wrong here?
heres what I would do. it even sends less bytes! (faster)
// to send
int snakeHead_position_x = 0;
int snakeHead_position_y = 0;
int direction_x = 0;
int direction_y = 0;
int bodyOffsetX = 0;
int bodyOffsetY = 0;
int amountBodies = 0;
NSString *package = [NSString stringWithFormat:#"%i|%i|%i|%i|%i|%i|%i",
snakeHead_position_x, snakeHead_position_y, direction_x,
direction_y, bodyOffsetX, bodyOffsetY, amountBodies];
NSData *data = [package dataUsingEncoding:NSASCIIStringEncoding];
assert(data); // this is critical don't remove!
//printf("sending %u bytes...\n", data.length);
[snakeSession sendData:data toPeers:snakePeers withDataMode:GKSendDataReliable error:nil];
// to retrieve
NSArray *intArray = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:#"|"];
int snakeHead_position_x = [intArray[0] intValue];
int snakeHead_position_y = [intArray[1] intValue];
int direction_x = [intArray[2] intValue];
int direction_y = [intArray[3] intValue];
int bodyOffsetX = [intArray[4] intValue];
int bodyOffsetY = [intArray[5] intValue];
int amountBodies = [intArray[6] intValue];
Related
Setting Timeout as Activity indicator keeps spinning when there is no response from webservice
I am using REST API to fetch data. I have two methods, one for ResponceSucces and other for responceFailure. In responce failure I simply dismiss the activity indicator. Sometimes it happens that data is not retrieved but still activity indicator keeps spinning infinitely. And ResponceFailure method is not Called. My question is can I set timeout interval to my web service, to check if response did not come, then activity indicator must be dismissed after some time for example 20/30 seconds. Below is my code: -(void)messagesGetSuccess:(FBListingsWebHandler*)handler response:(NSDictionary*)response { [MBProgressHUD hideHUDForView:self.view animated:YES]; [[FBModelManager sharedModelManager].messages removeAllObjects]; NSArray *messagesArray = [response objectForKey:#"message"]; if([[FBUserManager sharedUserManager] userType] == kUserShipper){ //extract usernames of transporters who placed bid on selected listing NSArray *userNames; NSMutableArray *transporterNames; NSDictionary *biddingsDic = [[FBModelManager sharedModelManager] getModelDictionary:kModelBiddings]; if ([biddingsDic count] > 0){ userNames = [[biddingsDic allValues] valueForKey:#"userName"]; NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:userNames]; NSSet *uniqueNames = [orderedSet set]; transporterNames = [[NSMutableArray alloc] initWithArray:[uniqueNames allObjects]]; } //add transporter records in messages dictionary who have messages for selected listing for (int i = 1; i < [messagesArray count]; i++) { NSMutableArray *modelArray = [[NSMutableArray alloc] init]; NSDictionary *groupedMsgDic = [messagesArray objectAtIndex:i]; int count = (int)[[[groupedMsgDic allValues] objectAtIndex:0] count]; for (int j = 0; j < count; j++) { FBMessagesModel *model = [[FBMessagesModel alloc] initWithMessageItems:[[[groupedMsgDic allValues] objectAtIndex:0] objectAtIndex:j]]; [modelArray addObject:model]; model = nil; } [[FBModelManager sharedModelManager].messages setObject:modelArray forKey:[[groupedMsgDic allKeys] objectAtIndex:0]]; //remove transporter usernames from array who have messages besides bid for selected listing if([transporterNames containsObject:[[groupedMsgDic allKeys] objectAtIndex:0]]){ [transporterNames removeObject:[[groupedMsgDic allKeys] objectAtIndex:0]]; } modelArray = nil; } //add transporter records in messages dictionary who placed bid but have no message for selected listing for (int i = 0; i < [transporterNames count]; i++) { NSString *path = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] photoPath]; int transporterId = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] userId]; NSString *objectForZeroMsgs = [NSString stringWithFormat:#"%#-%d",path,transporterId]; [[FBModelManager sharedModelManager].messages setObject:objectForZeroMsgs forKey:[transporterNames objectAtIndex:i]]; } transporterNames = nil; // [self tableView:self.shipperGroupedMessagesTableView_ numberOfRowsInSection:0]; [self.shipperGroupedMessagesTableView_ reloadData]; }else if([[FBUserManager sharedUserManager] userType] == kUserTransporter){ for (int i = 1; i < [messagesArray count]; i++) { FBMessagesModel *model = [[FBMessagesModel alloc] initWithMessageItems:[messagesArray objectAtIndex:i]]; [[FBModelManager sharedModelManager].messages setObject:model forKey:[NSString stringWithFormat:#"%d",model.mailId]]; if(model.mailMessage && ![model.mailMessage isEqualToString:#""]){ [self createMessageBubble:model]; } model = nil; } [self.bubbleTableView_ reloadData]; } } -(void)messagesGetFailure:(FBListingsWebHandler*)handler { [MBProgressHUD hideHUDForView:self.view animated:YES]; [[FBModelManager sharedModelManager].messages removeAllObjects]; if([[FBUserManager sharedUserManager] userType] == kUserTransporter){ [self.bubbleTableView_ reloadData]; } else if([[FBUserManager sharedUserManager] userType] == kUserShipper){ if([[FBModelManager sharedModelManager].messages count] == 0){ NSDictionary *biddingsDic = [[FBModelManager sharedModelManager] getModelDictionary:kModelBiddings]; if ([biddingsDic count] > 0){ NSArray *userNames = [[biddingsDic allValues] valueForKey:#"userName"]; NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:userNames]; NSSet *uniqueNames = [orderedSet set]; NSArray *transporterNames = [uniqueNames allObjects]; [[FBModelManager sharedModelManager].messages removeAllObjects]; for (int i = 0; i < [transporterNames count]; i++) { NSString *path = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] photoPath]; int transporterId = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] userId]; NSString *objectForZeroMsgs = [NSString stringWithFormat:#"%#-%d",path,transporterId]; [[FBModelManager sharedModelManager].messages setObject:objectForZeroMsgs forKey:[transporterNames objectAtIndex:i]]; } [self.shipperGroupedMessagesTableView_ reloadData]; }else{ [self addNoMessagesLabel]; } } [self.shipperGroupedMessagesTableView_ reloadData]; } } I am adding a screenshot.
Route drawing on Google Maps for iOS not following the street lines
I'm developing an iOS app which is using Google Directions API to draw routes on maps which are provided by Google Maps SDK. It works well on small distance although when I zoom the map camera very close I see that the route polylines are often getting out of the streets. When the distance is longer it's a real disaster and it's not following the streets curves if I zoom in. I'm getting the points from the overview-polyline which I receive from the Directions API but it seems like the polyline is not that poly as I want. On Android it works perfectly. Could it be that Google sends different directions to iOS than Android? Has some of you had the same problem as me? EDIT: -(int) requestDirecionsAndshowOnMap:(GMSMapView *)aMapView{ NSArray* mode=[[NSArray alloc]initWithObjects:#"transit",#"bicycling",#"walking",#"driving", nil]; NSString *depart=[[NSString alloc] initWithFormat:#""]; NSString *origin=[[NSString alloc] initWithFormat:#""]; NSString *destination=[[NSString alloc] initWithFormat:#""]; if (self.setLanguage) self.setLanguage=[NSString stringWithFormat:#"language=%#",self.setLanguage]; else self.setLanguage=#"language=en"; if (searchModeOption==0) { if (self.departDate==nil) { self.departDate=[NSDate date]; } depart=[NSString stringWithFormat:#"&departure_time=%i",(int)[self.departDate timeIntervalSince1970]]; } if (self.origin) { origin=[NSString stringWithFormat:#"origin=%#",self.origin]; }else if (self.originCoordinate.latitude && self.originCoordinate.longitude){ origin=[NSString stringWithFormat:#"origin=%f,%f",self.originCoordinate.latitude,self.originCoordinate.longitude]; }else{ NSLog(#"No origin setted"); return -1; } if (self.destination) { destination=[NSString stringWithFormat:#"destination=%#",self.destination]; }else if (self.destinationCoordinate.latitude && self.destinationCoordinate.longitude){ destination=[NSString stringWithFormat:#"destination=%f,%f",self.destinationCoordinate.latitude,self.destinationCoordinate.longitude]; }else{ NSLog(#"No destination setted"); return -1; } NSString* URLforRequest=[[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?%#&%#&sensor=false&%#&alternative=false&mode=%#%#",origin,destination,self.setLanguage,[mode objectAtIndex:searchModeOption],depart] stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]; // NSLog(#"%#",URLforRequest); NSURLRequest *requests = [NSURLRequest requestWithURL:[NSURL URLWithString:URLforRequest]]; [NSURLConnection sendAsynchronousRequest:requests queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ if (error==nil && data) { // NSLog(#"%#",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); directions = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; if (error) { NSLog(#"%#",error); } NSString* status=[directions objectForKey:#"status"]; NSLog(#"Status: %#", status); if ([status isEqualToString:#"OK"]) { [self decodeResult]; if (aMapView) [self showOnMap:aMapView]; } }else NSLog(#"%#",error); [[NSNotificationCenter defaultCenter] postNotificationName:#"Request Done" object:nil]; }]; return 0; } -(void) decodeResult{ self.destination=[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"] objectAtIndex:0] objectForKey:#"end_address"]; self.distance=[[[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"] objectAtIndex:0] objectForKey:#"distance"] objectForKey:#"text"] doubleValue]; self.duration=[[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"] objectAtIndex:0] objectForKey:#"duration"] objectForKey:#"text"]; //Get Array of Instructions self.instrunctions=[[NSMutableArray alloc] init]; for (int n=0; n<[[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"] objectAtIndex:0] objectForKey:#"steps"]count]; n++) { [self.instrunctions addObject:[[[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"] objectAtIndex:0] objectForKey:#"steps"] objectAtIndex:n] objectForKey:#"html_instructions"]]; } //Get Overview Polyline NSString *polystring=[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"overview_polyline"] objectForKey:#"points"]; NSMutableArray* decodedpolystring=[self decodePolyLine:polystring]; int numberOfCC=[decodedpolystring count]; GMSMutablePath *path = [GMSMutablePath path]; for (int index = 0; index < numberOfCC; index++) { CLLocation *location = [decodedpolystring objectAtIndex:index]; CLLocationCoordinate2D coordinate = location.coordinate; [path addLatitude:coordinate.latitude longitude:coordinate.longitude]; } self.overviewPolilyne= [GMSPolyline polylineWithPath:path]; //Get Coordinates of origin and destination to be displayed on a map float lat=[[[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"]objectAtIndex:0] objectForKey:#"end_location"] objectForKey:#"lat"] floatValue]; float lng=[[[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"]objectAtIndex:0] objectForKey:#"end_location"] objectForKey:#"lng"] floatValue]; CLLocationCoordinate2D tmp; tmp.latitude=lat; tmp.longitude=lng; self.destinationCoordinate=tmp; lat=[[[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"]objectAtIndex:0] objectForKey:#"start_location"] objectForKey:#"lat"] floatValue]; lng=[[[[[[[directions objectForKey:#"routes"] objectAtIndex:0] objectForKey:#"legs"]objectAtIndex:0] objectForKey:#"start_location"] objectForKey:#"lng"] floatValue]; tmp.latitude=lat; tmp.longitude=lng; self.originCoordinate=tmp; } -(NSMutableArray *)decodePolyLine:(NSString *)encodedStr { NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]]; [encoded appendString:encodedStr]; [encoded replaceOccurrencesOfString:#"\\\\" withString:#"\\" options:NSLiteralSearch range:NSMakeRange(0, [encoded length])]; NSInteger len = [encoded length]; NSInteger index = 0; NSMutableArray *array = [[NSMutableArray alloc] init]; NSInteger lat=0; NSInteger lng=0; while (index < len) { NSInteger b; NSInteger shift = 0; NSInteger result = 0; do { b = [encoded characterAtIndex:index++] - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = [encoded characterAtIndex:index++] - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1)); lng += dlng; NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5]; NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5]; CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]]; [array addObject:location]; } return array; } -(void)showOnMap:(GMSMapView *)aMapView{ GMSPolyline *polyline =self.overviewPolilyne; polyline.strokeColor = [UIColor blueColor]; polyline.strokeWidth = 2.f; //polyline.geodesic = YES; polyline.map = aMapView; } UPDATE: I had to process every step's polyline, not just the overview-polyline. Now it works perfectly. Here's the code I'm using now: // Get polyline GMSMutablePath *path = [GMSMutablePath path]; NSMutableArray *polyLinesArray = [[NSMutableArray alloc] init]; int zero=0; NSArray *steps = [[[[[directions objectForKey:#"routes"] objectAtIndex:zero] objectForKey:#"legs"] objectAtIndex:0] objectForKey:#"steps"]; for (int i=0; i<[[[[[[directions objectForKey:#"routes"] objectAtIndex:zero] objectForKey:#"legs"] objectAtIndex:0] objectForKey:#"steps"]count]; i++) { NSString* encodedPoints =[[[steps objectAtIndex:i]objectForKey:#"polyline"]valueForKey:#"points"]; polyLinesArray = [self decodePolyLine:encodedPoints]; NSUInteger numberOfCC=[polyLinesArray count]; for (NSUInteger index = 0; index < numberOfCC; index++) { CLLocation *location = [polyLinesArray objectAtIndex:index]; CLLocationCoordinate2D coordinate = location.coordinate; [path addLatitude:coordinate.latitude longitude:coordinate.longitude]; if (index==0) { [self.coordinates addObject:location]; } } } self.overviewPolilyne = [GMSPolyline polylineWithPath:path]; What I basically did before was that I was getting and working only with the information I'm receiving in the routes while if you check the JSON file you're receiving from Google Directions API, you'll see that you receive much more information in the <legs> and the <steps>. This is the information we need to produce the proper results and the right polyline. Good luck! :)
NSString to char my[16]
I am having NSString like : NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45"; how can i convert it to char array as shown below: char keyPtr[16] = {225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45} can anyone help! Thanks
NSString *input = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45"; char output[16]; NSArray *elements = [input componentsSeparatedByString:#","]; NSAssert([elements count] == 16, #"Input has wrong number of elements"); unsigned index = 0; for (NSString *element in elements) { int value = [element intValue]; NSAssert(value >= 0 && value <= 255, #"Element is invalid"); output[index++] = (char)value; } Note: You probably should be using a int[], and not char[], for output.
NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45"; NSArray *array = [str componentsSeparatedByString:#","]; Then use this in a for loop or something to add to your char array: char* myLilChar = [[array objectAtIndex:i] UTF8String]; Cheers :)
If you want to be as you said, use below NSString *str = #"225,0,190,169,236,236,113,97,43,102,217,8,113,201,50,45"; NSArray *array = [str componentsSeparatedByString:#","]; unsigned char keyPtr[array.count]; for(int i=0;i<array.count;i++) keyPtr[i] = (unsigned char)[[array objectAtIndex:i] intValue];
How do I convert a byte array to UIImage
I have a webservice which sends me back an array of bytes like this: <ax23:IMGBLOB>-119,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,100,0,0,0,106,8,3,0,0,0,125,54,4,22,0,0,0,51,80,76,84,69,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-73,-107,-30,-126,0,0,0,16,116,82,78,83,0,16,32,48,64,80,96,112,-128,-112,-96,-80,-64,-48,-32,-16,84,-32,-88,-56,0,0,2,126,73,68,65,84,120,-38,-19,90,65,-110,-124,32,12,4,68,64,69,-32,-1,-81,-35,-53,-78,-96,40,4,-79,-70,118,-86,-90,-113,51,106,-101,116,-120,33,-127,-3,43,72,101,-84,13,127,-80,-42,40,-7,42,-63,100,108,-72,-124,53,-45,75,38,-84,62,84,-32,-41,97,-125,-72,118,-95,9,-89,-7,0,-123,-56,-115,-88,-101,35,-98,90,-79,-122,14,-84,-113,-84,49,62,116,-63,-101,126,-71,-9,112,-58,-66,25,45,127,-95,-51,118,113,-127,-20,52,-29,124,-1,34,121,-31,78,-71,-100,-119,76,-113,-32,-5,-111,65,-117,-37,43,-11,-23,82,65,118,-107,63,40,42,91,-21,-24,-96,12,-47,101,-22,64,33,8,-122,31,104,20,-123,99,9,9,-106,104,-67,-80,-7,123,-79,38,-78,-73,114,51,35,99,118,29,44,-21,-45,-27,-59,-13,59,-87,-66,-14,-118,117,66,-91,120,89,104,-102,-69,7,57,124,114,20,-11,101,-118,119,-2,40,-37,-91,69,35,111,99,-60,-25,28,99,44,-2,46,46,-9,-100,99,-108,101,-81,-28,-85,-56,49,-50,98,-86,-126,56,-50,6,-64,93,41,75,-23,44,63,13,86,29,-2,-34,97,38,69,-33,32,-44,-83,-61,-72,-89,-26,4,122,102,-14,-68,-8,-93,16,100,80,-106,-14,-123,69,52,113,102,47,96,-114,79,19,-105,-122,88,-10,10,-74,43,83,-72,-49,-87,-57,33,-82,84,-47,45,-43,-71,-115,5,92,-97,-10,-102,37,-72,104,72,-43,126,111,120,-81,41,46,91,-20,-51,-16,-115,-9,-88,94,83,100,-15,-53,116,79,18,97,37,113,-35,23,-17,-19,99,30,-72,5,-79,-24,45,-77,-108,63,-77,-22,54,9,-67,-24,-43,39,-17,-104,40,123,-101,-124,94,-58,-120,83,2,-77,77,111,-79,112,-126,-99,-88,-2,-78,-57,39,24,2,73,-62,-62,-119,53,-5,49,-128,101,23,73,-16,21,9,-53,-57,-86,72,73,35,73,112,-110,17,-18,81,-71,93,59,-103,36,-63,-118,-74,40,38,-41,125,35,-112,-108,48,-68,-107,-118,109,78,98,-70,72,8,-27,-84,73,36,-55,119,68,18,-54,86,-79,-44,-102,16,92,44,84,-79,93,74,35,7,73,74,-97,1,72,66,-104,-21,36,60,102,-78,33,18,-53,10,8,8,9,-64,93,31,41,-4,90,13,97,-56,98,-124,-92,21,72,-126,28,77,-11,27,37,-43,67,62,90,-112,-49,47,-94,-112,24,40,-119,4,-71,36,-126,20,119,-112,50,21,89,112,-89,-51,68,-101,-60,78,-99,91,7,-56,38,8,-79,-99,-125,108,76,-79,91,-20,-9,-101,5,54,122,6,-46,-10,64,52,112,32,-83,40,68,83,13,-47,30,-124,52,58,17,45,91,68,-13,25,-46,70,71,12,4,16,-93,13,-64,-112,102,37,-113,-101,-74,-66,113,-45,22,18,7,98,112,6,29,1,-30,-121,-103,-8,-79,108,57,96,118,-75,1,-77,43,6,-52,-128,81,57,116,-24,-113,63,-66,-128,63,-120,-127,63,82,66,63,28,99,56,-2,-104,15,-2,-64,-46,-8,-47,-85,47,-66,-8,-30,-77,-16,3,-74,-58,-81,-89,-116,-22,56,-74,0,0,0,0,73,69,78,68,-82,66,96,-126,####</ax23:IMGBLOB> This array of bytes are used in Java for obtaining an image, I've been trying with several methods without success, I will post one of them below: -(UIImageView *)convierteImagen: (NSMutableString *)cadenaImagen{ //NSString to NSData (temporary) NSData *tempData = [cadenaImagen dataUsingEncoding:NSUTF8StringEncoding]; //NSLog(#"datos crudos: %#", tempData); //2.NSData to Bytes const void *bytes2 = [tempData bytes]; int8_t *bytes = (int8_t*)bytes2; int len = tempData.length; cadenaImagen = [[NSMutableString alloc]init]; [cadenaImagen appendString:#"["]; for (int i = 0; i < len; i++) { if (i) [cadenaImagen appendString:#","]; [cadenaImagen appendFormat:#"%d", bytes[i]]; } [cadenaImagen appendString:#"]"]; //3.Bytes to NSData NSData *datos2 = [NSData dataWithBytes:bytes length:len]; return [[UIImageView alloc]initWithImage:[UIImage imageWithData:datos2]]; } and the way I call this method is: - (void)viewDidLoad { [super viewDidLoad]; NSMutableString *imagen = [[NSMutableString alloc] initWithString:#"-119,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,100,0,0,0,106,8,3,0,0,0,125,54,4,22,0,0,0,51,80,76,84,69,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-73,-107,-30,-126,0,0,0,16,116,82,78,83,0,16,32,48,64,80,96,112,-128,-112,-96,-80,-64,-48,-32,-16,84,-32,-88,-56,0,0,2,126,73,68,65,84,120,-38,-19,90,65,-110,-124,32,12,4,68,64,69,-32,-1,-81,-35,-53,-78,-96,40,4,-79,-70,118,-86,-90,-113,51,106,-101,116,-120,33,-127,-3,43,72,101,-84,13,127,-80,-42,40,-7,42,-63,100,108,-72,-124,53,-45,75,38,-84,62,84,-32,-41,97,-125,-72,118,-95,9,-89,-7,0,-123,-56,-115,-88,-101,35,-98,90,-79,-122,14,-84,-113,-84,49,62,116,-63,-101,126,-71,-9,112,-58,-66,25,45,127,-95,-51,118,113,-127,-20,52,-29,124,-1,34,121,-31,78,-71,-100,-119,76,-113,-32,-5,-111,65,-117,-37,43,-11,-23,82,65,118,-107,63,40,42,91,-21,-24,-96,12,-47,101,-22,64,33,8,-122,31,104,20,-123,99,9,9,-106,104,-67,-80,-7,123,-79,38,-78,-73,114,51,35,99,118,29,44,-21,-45,-27,-59,-13,59,-87,-66,-14,-118,117,66,-91,120,89,104,-102,-69,7,57,124,114,20,-11,101,-118,119,-2,40,-37,-91,69,35,111,99,-60,-25,28,99,44,-2,46,46,-9,-100,99,-108,101,-81,-28,-85,-56,49,-50,98,-86,-126,56,-50,6,-64,93,41,75,-23,44,63,13,86,29,-2,-34,97,38,69,-33,32,-44,-83,-61,-72,-89,-26,4,122,102,-14,-68,-8,-93,16,100,80,-106,-14,-123,69,52,113,102,47,96,-114,79,19,-105,-122,88,-10,10,-74,43,83,-72,-49,-87,-57,33,-82,84,-47,45,-43,-71,-115,5,92,-97,-10,-102,37,-72,104,72,-43,126,111,120,-81,41,46,91,-20,-51,-16,-115,-9,-88,94,83,100,-15,-53,116,79,18,97,37,113,-35,23,-17,-19,99,30,-72,5,-79,-24,45,-77,-108,63,-77,-22,54,9,-67,-24,-43,39,-17,-104,40,123,-101,-124,94,-58,-120,83,2,-77,77,111,-79,112,-126,-99,-88,-2,-78,-57,39,24,2,73,-62,-62,-119,53,-5,49,-128,101,23,73,-16,21,9,-53,-57,-86,72,73,35,73,112,-110,17,-18,81,-71,93,59,-103,36,-63,-118,-74,40,38,-41,125,35,-112,-108,48,-68,-107,-118,109,78,98,-70,72,8,-27,-84,73,36,-55,119,68,18,-54,86,-79,-44,-102,16,92,44,84,-79,93,74,35,7,73,74,-97,1,72,66,-104,-21,36,60,102,-78,33,18,-53,10,8,8,9,-64,93,31,41,-4,90,13,97,-56,98,-124,-92,21,72,-126,28,77,-11,27,37,-43,67,62,90,-112,-49,47,-94,-112,24,40,-119,4,-71,36,-126,20,119,-112,50,21,89,112,-89,-51,68,-101,-60,78,-99,91,7,-56,38,8,-79,-99,-125,108,76,-79,91,-20,-9,-101,5,54,122,6,-46,-10,64,52,112,32,-83,40,68,83,13,-47,30,-124,52,58,17,45,91,68,-13,25,-46,70,71,12,4,16,-93,13,-64,-112,102,37,-113,-101,-74,-66,113,-45,22,18,7,98,112,6,29,1,-30,-121,-103,-8,-79,108,57,96,118,-75,1,-77,43,6,-52,-128,81,57,116,-24,-113,63,-66,-128,63,-120,-127,63,82,66,63,28,99,56,-2,-104,15,-2,-64,-46,-8,-47,-85,47,-66,-8,-30,-77,-16,3,-74,-58,-81,-89,-116,-22,56,-74,0,0,0,0,73,69,78,68,-82,66,96,-126"]; [self.view addSubview:[self convierteImagen:imagen]]; } Any help I will appreciate :)
try this: -(UIImageView *)convierteImagen: (NSMutableString *)cadenaImagen{ NSArray *strings = [cadenaImagen componentsSeparatedByString:#","]; unsigned c = strings.count; uint8_t *bytes = malloc(sizeof(*bytes) * c); unsigned i; for (i = 0; i < c; i++) { NSString *str = [strings objectAtIndex:i]; int byte = [str intValue]; bytes[i] = (uint8_t)byte; } NSData *datos = [NSData dataWithBytes:bytes length:c]; UIImage *image = [UIImage imageWithData:datos]; return [[UIImageView alloc]initWithImage:image]; } on viewdidLoad is the same code you put: - (void)viewDidLoad { [super viewDidLoad]; NSMutableString *imagen = [[NSMutableString alloc] initWithString:#"-119,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,100,0,0,0,106,8,3,0,0,0,125,54,4,22,0,0,0,51,80,76,84,69,0,0,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-73,-107,-30,-126,0,0,0,16,116,82,78,83,0,16,32,48,64,80,96,112,-128,-112,-96,-80,-64,-48,-32,-16,84,-32,-88,-56,0,0,2,126,73,68,65,84,120,-38,-19,90,65,-110,-124,32,12,4,68,64,69,-32,-1,-81,-35,-53,-78,-96,40,4,-79,-70,118,-86,-90,-113,51,106,-101,116,-120,33,-127,-3,43,72,101,-84,13,127,-80,-42,40,-7,42,-63,100,108,-72,-124,53,-45,75,38,-84,62,84,-32,-41,97,-125,-72,118,-95,9,-89,-7,0,-123,-56,-115,-88,-101,35,-98,90,-79,-122,14,-84,-113,-84,49,62,116,-63,-101,126,-71,-9,112,-58,-66,25,45,127,-95,-51,118,113,-127,-20,52,-29,124,-1,34,121,-31,78,-71,-100,-119,76,-113,-32,-5,-111,65,-117,-37,43,-11,-23,82,65,118,-107,63,40,42,91,-21,-24,-96,12,-47,101,-22,64,33,8,-122,31,104,20,-123,99,9,9,-106,104,-67,-80,-7,123,-79,38,-78,-73,114,51,35,99,118,29,44,-21,-45,-27,-59,-13,59,-87,-66,-14,-118,117,66,-91,120,89,104,-102,-69,7,57,124,114,20,-11,101,-118,119,-2,40,-37,-91,69,35,111,99,-60,-25,28,99,44,-2,46,46,-9,-100,99,-108,101,-81,-28,-85,-56,49,-50,98,-86,-126,56,-50,6,-64,93,41,75,-23,44,63,13,86,29,-2,-34,97,38,69,-33,32,-44,-83,-61,-72,-89,-26,4,122,102,-14,-68,-8,-93,16,100,80,-106,-14,-123,69,52,113,102,47,96,-114,79,19,-105,-122,88,-10,10,-74,43,83,-72,-49,-87,-57,33,-82,84,-47,45,-43,-71,-115,5,92,-97,-10,-102,37,-72,104,72,-43,126,111,120,-81,41,46,91,-20,-51,-16,-115,-9,-88,94,83,100,-15,-53,116,79,18,97,37,113,-35,23,-17,-19,99,30,-72,5,-79,-24,45,-77,-108,63,-77,-22,54,9,-67,-24,-43,39,-17,-104,40,123,-101,-124,94,-58,-120,83,2,-77,77,111,-79,112,-126,-99,-88,-2,-78,-57,39,24,2,73,-62,-62,-119,53,-5,49,-128,101,23,73,-16,21,9,-53,-57,-86,72,73,35,73,112,-110,17,-18,81,-71,93,59,-103,36,-63,-118,-74,40,38,-41,125,35,-112,-108,48,-68,-107,-118,109,78,98,-70,72,8,-27,-84,73,36,-55,119,68,18,-54,86,-79,-44,-102,16,92,44,84,-79,93,74,35,7,73,74,-97,1,72,66,-104,-21,36,60,102,-78,33,18,-53,10,8,8,9,-64,93,31,41,-4,90,13,97,-56,98,-124,-92,21,72,-126,28,77,-11,27,37,-43,67,62,90,-112,-49,47,-94,-112,24,40,-119,4,-71,36,-126,20,119,-112,50,21,89,112,-89,-51,68,-101,-60,78,-99,91,7,-56,38,8,-79,-99,-125,108,76,-79,91,-20,-9,-101,5,54,122,6,-46,-10,64,52,112,32,-83,40,68,83,13,-47,30,-124,52,58,17,45,91,68,-13,25,-46,70,71,12,4,16,-93,13,-64,-112,102,37,-113,-101,-74,-66,113,-45,22,18,7,98,112,6,29,1,-30,-121,-103,-8,-79,108,57,96,118,-75,1,-77,43,6,-52,-128,81,57,116,-24,-113,63,-66,-128,63,-120,-127,63,82,66,63,28,99,56,-2,-104,15,-2,-64,-46,-8,-47,-85,47,-66,-8,-30,-77,-16,3,-74,-58,-81,-89,-116,-22,56,-74,0,0,0,0,73,69,78,68,-82,66,96,-126"]; [self.view addSubview:[self convierteImagen: imagen]]; } this is what I got with your byte array: so I think this should solve your problem ;)
Collect string values and add into array
I am writing an app where I want to collect names and phone numbers from a list and add them into an array. How do I do this? I could retrieve first name and last name, but I don't get how to add a phone number in the below code as it is in a different for loop. It might look simple but I am stuck as I am new. for (i = 0; i < [list count]; i++) { NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty); NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty); NSMutableArray *name = [NSMutableArray array]; if(firstName != nil) [name addObject:firstName]; if(lastName != nil) [name addObject:lastName];*/ [self displaynames:name]; ABMultiValueRef mobile=ABRecordCopyValue(contactPerson, kABPersonPhoneProperty); for (int k=0;k<ABMultiValueGetCount(mobile); k++) { NSString *mobileNo = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(mobile, k); NSLog(#"mobile number: %#",mobileNo); } } - (void)displaynames:(NSMutableArray*)names { for (NSMutableArray* name in names) { NSLog(#"MyResult:%# %#",[names objectAtIndex:0],[names objectAtIndex:1]); } } So in the above code I am able to get the first name and last name from the list and add them into the array, similarly how do I get mobile phone number and add into the same array and get the result in the displayNames: function as it is another for loop. Can someone please edit the code and tell me what changes I have to make in the above code. Also in the result everything is being displayed twice why so?
NSMutableArray *contactList=[[NSMutableArray alloc] init]; for (int i=0; i<4; i++) { NSMutableDictionary *contactInfo=[[NSMutableDictionary alloc] init]; for (int i = 0; i < [list count]; i++) { NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty); NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty); if (![firstName isEqualToString:#""]) { [contactInfo setValue:firstName forKey:#"firstName"]; } if (![lastName isEqualToString:#""]) { [contactInfo setValue:lastName forKey:#"lastName"]; } NSMutableArray *mobileNoArray=[[NSMutableArray alloc] initWithCapacity:ABMultiValueGetCount(mobile)]; ABMultiValueRef mobile=ABRecordCopyValue(contactPerson, kABPersonPhoneProperty); for (int k=0;k<ABMultiValueGetCount(mobile); k++) { NSString *mobileNo = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(mobile, k); [mobileNoArray addObject:mobileNo]; } if (mobileNoArray.count!=0) { [contactInfo setObject:mobileNoArray forKey:#"mobileNo"] } } [contactList addObject:contactInfo]; NSLog(#"contact info == %#",contactInfo); } NSLog(#"contact list array is %#",contactList);
So, instead using Array you have to use Dictionary to store FirstName, LastName and MobileNo with keyvalue Pair. If you have multiple user than use Array as upper layer, means add your user dictionary into array and when ever you want a user write the code: for(NSDictionary *userDic in yourArray) { NSString *fName = [userDic valueForKey:#"FirstName"]; ... } This is one of the way...
You can try to add the user info in a dictionary or create a model user object and store in the array. So all the information stays encapsulated in a single object. self.users = [NSMutableArray array]; for (i = 0; i < [list count]; i++) { NSString *firstName = ... NSString *lastName = ... NSString *mobileNumber = ... NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; if(firstName) userInfo[#"FirstName"] = firstName; if(lastName) userInfo[#"LastName"] = lastName; if(mobileNumber) userInfo[#"MobileNumber"] = mobileNumber; [self.users addObject:userInfo]; } You can enumerate using [self.users enumerateObjectsUsingBlock:^(NSDictionary * userInfo, NSUInteger idx, BOOL *stop) { NSString *firstName = userInfo[#"FirstName"]; NSString *mobileNumber = userInfo[#"MobileNumber"]; }]; Searching for a single user for a name NSPredicate *predicate = [NSPredicate predicateWithFormat:#"FirstName == %#",#"aUserName"]; NSDictionary *userInfo = [[self.users filteredArrayUsingPredicate:predicate]lastObject];
Try the following steps: NSMutableArray *firstNames; NSMutableArray *LastNames; NSMutableArray *Mobile_numbers; NSMutableArray *type_array; NSMutableArray *firstandlast; ........ -(void)get_arr { ABAddressBookRef addressBook = ABAddressBookCreate(); NSArray *arrayOfPeople = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook); NSUInteger index = 0; firstNames = [[NSMutableArray alloc] init]; Mobile_numbers = [[NSMutableArray alloc] init]; type_array=[[NSMutableArray alloc]init ]; LastNames=[[NSMutableArray alloc]init ]; NSMutableArray *firstandlast; #try { for(index = 0; index<=([arrayOfPeople count]-1); index++) { ABRecordRef currentPerson = (__bridge ABRecordRef)[arrayOfPeople objectAtIndex:index]; NSString *type; ABMultiValueRef phones = (ABMultiValueRef)ABRecordCopyValue(currentPerson, kABPersonPhoneProperty); for (int i=0; i < ABMultiValueGetCount(phones); i++) { //NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phones, i); ////NSLog(#"%#", phone); mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i); //NSLog(#"MOG:%#",mobileLabel); if([mobileLabel isEqualToString:#"_$!<Mobile>!$_"]||[mobileLabel isEqualToString:#"_$!<Main>!$_"]) { //NSLog(#"mobile:"); type=#"mobile"; } else if ([mobileLabel isEqualToString:#"_$!<Work>!$_"]) { //NSLog(#"Work:"); type=#"Work"; } else if ([mobileLabel isEqualToString:#"_$!<Home>!$_"]) { //NSLog(#"Home:"); type=#"Home"; } else if ([mobileLabel isEqualToString:#"_$!<Other>!$_"] ) { //NSLog(#"Other:"); type=#"Other"; } mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i); //NSLog(#"GG:%#",mobile); mobile = [mobile stringByReplacingOccurrencesOfString:#"-" withString:#""]; mobile = [mobile stringByReplacingOccurrencesOfString:#"(" withString:#""]; mobile = [mobile stringByReplacingOccurrencesOfString:#")" withString:#""]; mobile = [mobile stringByReplacingOccurrencesOfString:#" " withString:#""]; [Mobile_numbers addObject:mobile]; [type_array addObject:type]; NSString *currentFirstName = (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonFirstNameProperty); ////NSLog(#"NAME:%#",currentFirstName); if ([currentFirstName length]!=0) { //NSLog(#"NAME:%#",currentFirstName); [firstNames addObject:currentFirstName]; } else { //NSLog(#"NAME:DUMMY"); currentFirstName=#""; [firstNames addObject:currentFirstName]; } NSString *currentLast = (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonLastNameProperty); ////NSLog(#"NAME:%#",currentFirstName); if ([currentLast length]!=0) { //NSLog(#"NAME:%#",currentLast); [LastNames addObject:currentLast]; } else { //NSLog(#"NAME:DUMMY"); currentLast=#""; [LastNames addObject:currentLast]; } NSString *temp_f_l=[NSString stringWithFormat:#"%# %#",currentFirstName,currentLast]; [firstandlast addObject:temp_f_l]; } NSLog(#"MOB:%#",Mobile_numbers); NSLog(#"TYPE:%#",type_array); NSLog(#"FN:%#",firstNames); NSLog(#"FN:%#",LastNames); NSLog(#"FN&LN:%#",firstandlast); } } #catch (NSException *exception) { //NSLog(#"CATCH"); } } In my Application. I am using this code to store Addressbook contents to Array. I hope it help for you.