VNSequenceRequestHandler VNTrackRectangleRequest iOS16 limit error - vision

On iOS 15 and lower all good, issue appear only on iOS 16.
+ (void)load
{
// test image with rect
CIImage * image = [ [ CIImage alloc ] initWithData:[ NSData dataWithContentsOfURL:[ NSURL URLWithString:#"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSSZRebToiMqFCochj1CzIQws9HSFhjrihw0g&usqp=CAU" ] ] ];
for (int i = 0; i < 1000; i++)
{
#autoreleasepool
{
VNSequenceRequestHandler * sequenceRequestHandler = [ [ VNSequenceRequestHandler alloc ] init ];
__block VNRectangleObservation * lastObservation = nil;
VNDetectRectanglesRequest * detectRequest = [ [ VNDetectRectanglesRequest alloc ] initWithCompletionHandler:^(VNRequest * request, NSError * error)
{
lastObservation = request.results.firstObject;
} ];
[ sequenceRequestHandler performRequests:[ NSArray arrayWithObject:detectRequest ] onCIImage:image error:nil ];
VNTrackRectangleRequest * trackRequest = [ [ VNTrackRectangleRequest alloc ] initWithRectangleObservation:lastObservation completionHandler:nil ];
NSError * error = nil;
[ sequenceRequestHandler performRequests:[ NSArray arrayWithObject:trackRequest ] onCIImage:image error:&error ];
if (error)
{
NSLog(#"error at %d", i);
}
}
}
}
It's appear for i==16
Error Domain=com.apple.vis Code=9 "Internal error: Exceeded maximum
allowed number of Trackers for a tracker type: VNRectangleTrackerType"
UserInfo={NSLocalizedDescription=Internal error: Exceeded maximum
allowed number of Trackers for a tracker type: VNRectangleTrackerType}
No memory leak detected by Instruments.
EDITED
I fix it in my way, maybe it help someone. iOS 16 don't release VNSequenceRequestHandler after nil it, you need performRequests with new VNTrackRectangleRequest.lastFrame = YES; on it.
if (#available(iOS 16.0, *))
{
VNTrackRectangleRequest * trackRequest = [ [ VNTrackRectangleRequest alloc ] initWithRectangleObservation:lastObservation ];
trackRequest.lastFrame = YES;
requestArray = [ NSArray arrayWithObject:trackRequest ];
[ sequenceRequestHandler performRequests:requestArray onCIImage:[ CIImage new ] error:nil ];
}

Related

newLibraryWithStitchedDescriptor fails with XPC Error

I'm trying to build a stitched metal kernel. My shader code is
[[stitchable]] float add(float a, float b) {
return a + b;
}
[[stitchable]] float load(constant float *a, uint32_t index) {
return a[index];
}
[[stitchable]] void store(device float *a, float value, uint32_t index) {
a[index] = value;
}
[[visible]] void two_inputs(constant float *a, constant float *b, device *c, uint32_t tid);
The driver code is
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> queue = [device newCommandQueue];
id<MTLLibrary> library = [device newDefaultLibrary];
NSArray *functions = #[
[library newFunctionWithName:#"add"],
[library newFunctionWithName:#"load"],
[library newFunctionWithName:#"store"]
];
MTLFunctionStitchingInputNode *srcA = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:0];
MTLFunctionStitchingInputNode *srcB = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:1];
MTLFunctionStitchingInputNode *srcC = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:2];
MTLFunctionStitchingInputNode *srcI = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:3];
MTLFunctionStitchingFunctionNode *loadA = [[MTLFunctionStitchingFunctionNode alloc] initWithName:#"load" arguments:#[srcA, srcI] controlDependencies:#[]];
MTLFunctionStitchingFunctionNode *loadB = [[MTLFunctionStitchingFunctionNode alloc] initWithName:#"load" arguments:#[srcA, srcI] controlDependencies:#[]];
MTLFunctionStitchingFunctionNode *add = [[MTLFunctionStitchingFunctionNode alloc] initWithName:#"load" arguments:#[loadA, loadB] controlDependencies:#[]];
MTLFunctionStitchingFunctionNode *storeC = [[MTLFunctionStitchingFunctionNode alloc] initWithName:#"load" arguments:#[srcC, add, srcI] controlDependencies:#[]];
MTLFunctionStitchingGraph *graph = [[MTLFunctionStitchingGraph alloc] initWithFunctionName:#"two_inputs" nodes:#[loadA, loadB, add] outputNode:storeC attributes:#[]];
MTLStitchedLibraryDescriptor *graphDescriptor = [MTLStitchedLibraryDescriptor new];
graphDescriptor.functions = functions;
graphDescriptor.functionGraphs = #[graph];
NSError *error = NULL;
id<MTLLibrary> graphLibrary = [device newLibraryWithStitchedDescriptor: graphDescriptor.functions error:&error];
NSLog(#"%#", error);
This is causing the metal compiler to fail with the error.
Compiler failed with XPC_ERROR_CONNECTION_INTERRUPTED
MTLCompiler: Compilation failed with XPC_ERROR_CONNECTION_INTERRUPTED on 1 try
...
Error Domain=MTLLibraryErrorDomain Code=3 "Compiler encountered an internal error" UserInfo={NSLocalizedDescription=Compiler encountered an internal error}
I'm trying to run this on an M1 mac.
It turns out the reason the Metal compiler was crashing was this line
MTLFunctionStitchingGraph *graph = [[MTLFunctionStitchingGraph alloc] initWithFunctionName:#"two_inputs" nodes:#[loadA, loadB, add] outputNode:storeC attributes:#[]];
should be
MTLFunctionStitchingGraph *graph = [[MTLFunctionStitchingGraph alloc] initWithFunctionName:#"two_inputs" nodes:#[loadA, loadB, add, storeC] outputNode:NULL attributes:#[]];
instead.

How to detect total available/free disk space on the iPhone/iPad device on iOS 11

In iOS 11, I am not able to get the correct free size of the device(disk space) from the Dictionary key NSFileSystemFreeSize. Instead giving 34.4 GB it gives 4 GB free space.
Below is the code I am using
pragma mark - Formatter
- (NSString *)memoryFormatter:(long long)diskSpace
{
NSString *formatted;
double bytes = 1.0 * diskSpace;
double megabytes = bytes / MB;
double gigabytes = bytes / GB;
if (gigabytes >= 1.0)
formatted = [NSString stringWithFormat:#"%.2f GB", gigabytes];
else if (megabytes >= 1.0)
formatted = [NSString stringWithFormat:#"%.2f MB", megabytes];
else
formatted = [NSString stringWithFormat:#"%.2f bytes", bytes];
return formatted;
}
#pragma mark - Methods
- (NSString *)totalDiskSpace {
long long space = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemSize] longLongValue];
return [self memoryFormatter:space];
}
- (NSString *)freeDiskSpace {
long long freeSpace = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] longLongValue];
return [self memoryFormatter:freeSpace];
}
- (NSString *)usedDiskSpace {
return [self memoryFormatter:[self usedDiskSpaceInBytes]];
}
- (CGFloat)totalDiskSpaceInBytes {
long long space = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemSize] longLongValue];
return space;
}
- (CGFloat)freeDiskSpaceInBytes {
long long freeSpace = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] longLongValue];
return freeSpace;
}
- (CGFloat)usedDiskSpaceInBytes {
long long usedSpace = [self totalDiskSpaceInBytes] - [self freeDiskSpaceInBytes];
return usedSpace;
}
OBJECTIVE C (converted)
- (uint64_t)freeDiskspace
{
uint64_t totalSpace = 0;
uint64_t totalFreeSpace = 0;
__autoreleasing NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
if (dictionary)
{
NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
NSLog(#"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
}
else
{
NSLog(#"Error Obtaining System Memory Info: Domain = %#, Code = %d", [error domain], [error code]);
}
return totalFreeSpace;
}
So if people have the problem of not getting the correct free size, use NSURL resourceValuesForKeys to get the free space.
[ fileURL resourceValuesForKeys:#[NSURLVolumeAvailableCapacityForImportantUsageKey ] error:&error];
double = availableSizeInBytes = [ results[NSURLVolumeAvailableCapacityForImportantUsageKey] doubleValue ];
Reference Why is `volumeAvailableCapacityForImportantUsage` zero?
Here's how I usually do it
func deviceRemainingFreeSpaceInBytes() -> Int64?
{
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
guard
let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: documentDirectory),
let freeSize = systemAttributes[.systemFreeSize] as? NSNumber
else {
// handle failure
return nil
}
return freeSize.int64Value // this returns bytes - scales as required for MB / GB
}
SWIFT 4:
func getFreeDiskspace() -> UInt64
{
let totalSpace: UInt64 = 0
let totalFreeSpace: UInt64 = 0
var error: Error? = nil
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last ?? "")
if dictionary
{
var fileSystemSizeInBytes = dictionary[.systemSize]
var freeFileSystemSizeInBytes = dictionary[.systemFreeSize]
totalSpace = fileSystemSizeInBytes as UInt64? ?? 0
totalFreeSpace = freeFileSystemSizeInBytes as UInt64? ?? 0
print("Memory Capacity of \((totalSpace / 1024) / 1024) MiB with \((totalFreeSpace / 1024) / 1024) MiB Free memory available.")
}
else
{
print("Error Obtaining System Memory Info: Domain = \((error as NSError?)?.domain), Code = \(Int(error.code))")
return totalFreeSpace
}
}

How to remove an object from other keys in a dictionary [Objective-C]?

I have an NSMutableDictionary as follows:
{ 0 = (1,5,6); 1 = (0,2,6,7); 2 = (1,7,8); 5 = (0,6,10,11); 6 =
(0,1,5,7,11,12)};
in the format of {NSNumber:NSMutableArray}
I want to remove every 0 that is there in every key or the keys for the values of '0'. What is a way to do it?
The expected outcome is:
{ 0 = (1,5,6); 1 = (2,6,7); 2 = (1,7,8); 5 = (6,10,11); 6 =
(1,5,7,11,12)};
I am looking for an elegant solution.
Use this assuming that your NSMutableArray is an NSNumber array, also the key 0 is removed in this improvement
Improved
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
dict[#0] = [NSMutableArray arrayWithObjects:#0,#10, nil];
dict[#1] = [NSMutableArray arrayWithObjects:#0,#10, nil];
dict[#2] = [NSMutableArray arrayWithObjects:#0,#7,#10, nil];
int valueToRemove = 0; //change this value for what you need
for (NSNumber * key in dict.allKeys) {
if([key intValue] == valueToRemove) {dict[key] = nil;}
dict[key] = [dict[key] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"intValue != %i",valueToRemove]];
}
NSLog(#"%#",dict);
CONSOLE LOG
2017-07-28 02:18:21.257 ArrayProblemQuestion[76557:1576267] {
1 = (
10
);
2 = (
7,
10
); }
if you want to loop only for certain keys then
NSMutableArray * array = [NSMutableArray arrayWithObjects:#1,#3,#0, nil];
for (NSNumber * key in [dict.allKeys filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"intValue IN %#",array]]) {
NSLog(#"%#",key);
}
this will loop only for the keys contained in array
Hope this helps
// This is your input
NSMutableDictionary *dicMain = [NSMutableDictionary new];
dicMain[#"0"] = #[#1,#5,#6];
dicMain[#"1"] = #[#0,#2,#6,#7];
dicMain[#"2"] = #[#1,#7,#8];
dicMain[#"5"] = #[#0,#6,#10,#11];
dicMain[#"6"] = #[#0,#1,#5,#7,#11,#12];
NSLog(#"%#",dicMain);
// Remove key from Dic if its having 0
if([[dicMain allKeys] containsObject:#"0"])
[dicMain removeObjectForKey:#"0"];
// Check each and every object into all key's that if its having 0 then it will remove
NSArray *aryAllKeys = [dicMain allKeys];
for(NSString *strKey in aryAllKeys)
{
NSMutableArray *aryNewValue = [NSMutableArray new];
NSArray *aryKeyValues = [dicMain objectForKey:strKey];
for(NSString *str in aryKeyValues)
{
if([str intValue] != 0)
{
[aryNewValue addObject:str];
}
}
// Set New array
[dicMain setObject:aryNewValue forKey:strKey];
}
NSLog(#"%#",dicMain);
The output of main Dic without removing 0:
{
1 = (
2,
6,
7
);
2 = (
1,
7,
8
);
5 = (
0,
6,
10,
11
);
6 = (
0,
1,
5,
7,
11,
12
);
}
After Removing 0:
{
1 = (
2,
6,
7
);
2 = (
1,
7,
8
);
5 = (
6,
10,
11
);
6 = (
1,
5,
7,
11,
12
);
}
I'd do something like this..
[myDict enumerateKeysAndObjectsUsingBlock:^(NSNumber * _Nonnull key,
NSMutableArray * _Nonnull array,
BOOL * _Nonnull stop) {
[array removeObject:#0];
}];
You can do like below. This is improvement of other answer with key '0'.
NSMutableDictionary *dict = [NSMutableDictionary new];
dict[#"0"] = #[#1,#5,#6];
dict[#"1"] = #[#0,#2,#6,#7];
dict[#"2"] = #[#1,#7,#8];
dict[#"5"] = #[#6,#10,#11];
dict[#"6"] = #[#0,#1,#5,#7,#11,#12];
int valueToRemove = 0; //change this value for what you need to remove
for (NSNumber * key in dict.allKeys) {
if([key intValue] == valueToRemove) {
dict[key] = [dict[key] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"intValue != %i",valueToRemove]];
}else{
dict[key] = [dict[key] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"intValue != %i",valueToRemove]];
}
}
NSLog(#"%#",dict);
And your expected output like this with key '0'.
{
0 = ( 1, 5, 6 );
1 = ( 2, 6, 7 );
2 = ( 1, 7, 8 );
5 = ( 6, 10, 11 );
6 = ( 1, 5, 7, 11, 12 );
}

Print UIImage metadata to label

I'm attempting to read the metadata produced by a UIImage when shot from the UIImagePicker, and I'm having some trouble.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
// get the metadata
NSDictionary *imageMetadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
NSLog (#"imageMetaData %#",imageMetadata);
This successfully prints the metadata dictionary to NSLog.
The issue I'm having is that I would like to access specific indices of the dictionary (such as FNumber, ISO, etc.) and print them to specific labels, but I can't figure out how to access the individual data.
Here is what I have tried so far to pull the data, but it doesn't seem to find the key (it returns as NULL):
NSLog(#"ISO: %#", imageMetadata[#"ISOSpeedRatings"]);
Based off of what NSLog prints for the dictionary, it seems as if there may be dictionaries within the dictionary, and that's what's throwing me off.
Here's what gets printed for the metadata:
imageMetaData {
DPIHeight = 72;
DPIWidth = 72;
Orientation = 6;
"{Exif}" = {
ApertureValue = "2.27500704749987";
BrightnessValue = "-0.6309286396300304";
ColorSpace = 1;
DateTimeDigitized = "2015:04:01 10:33:37";
DateTimeOriginal = "2015:04:01 10:33:37";
ExposureBiasValue = 0;
ExposureMode = 0;
ExposureProgram = 2;
ExposureTime = "0.06666666666666667";
FNumber = "2.2";
Flash = 24;
FocalLenIn35mmFilm = 29;
FocalLength = "4.15";
ISOSpeedRatings = (
320
);
LensMake = Apple;
LensModel = "iPhone 6 back camera 4.15mm f/2.2";
LensSpecification = (
"4.15",
"4.15",
"2.2",
"2.2"
);
MeteringMode = 5;
PixelXDimension = 3264;
PixelYDimension = 2448;
SceneType = 1;
SensingMethod = 2;
ShutterSpeedValue = "3.907056515078773";
SubjectArea = (
1631,
1223,
1795,
1077
);
SubsecTimeDigitized = 705;
SubsecTimeOriginal = 705;
WhiteBalance = 0;
};
"{MakerApple}" = {
1 = 2;
14 = 0;
2 = <0f000b00 06000900 04005000 a900b100 b700bb00 c400cd00 cd00a400 b100c700 14000b00 05000900 06000a00 8a00a800 b000b800 c300cb00 c900cd00 b300a600 2f000700 06000700 0a000400 3500a400 ab00b300 bc00c300 cf00d300 b4007f00 3f000700 09000700 0a000700 05007100 a100af00 b500c200 ce00cd00 a9006b00 1f000a00 0b000900 0a000c00 05001e00 9c00aa00 b400c200 cc00d000 d4005700 2b001900 0d001000 10000d00 08000600 5b00a700 b300bf00 cb00d500 e3008600 eb002800 1a001700 14000c00 0b000700 10009400 b100c000 ce00e000 f400bd00 cf013e00 2a001200 17000f00 0d000800 07004200 b100c000 d300e900 fd000401 ff011101 1d000700 16001400 09000700 07000900 8900bf00 d800ec00 07011f01 10021102 39000b00 10001900 0e000800 0a000700 2c00bf00 dd00f400 0b012401 1e023802 1f010d00 07001900 16000c00 0c000800 21007000 c500f400 0a012e01 10022202 01022500 08001000 18001100 0d001800 1601cc00 d100eb00 09012201 fb011002 26020401 0f000700 16001400 3200e801 6001b000 ce00f400 08011601 e1010602 1a020302 23001700 21002300 84009300 9f00ad00 bf00e800 02011401 ca01fc01 19024002 08013d00 3500ca00 7c009200 9e00ab00 c200d700 f8000a01 b401f101 1b024802 28023000 4a007f00 7f008e00 a000b100 bd00d000 ec00fe00>;
3 = {
epoch = 0;
flags = 1;
timescale = 1000000000;
value = 777291330499583;
};
4 = 1;
5 = 128;
6 = 123;
7 = 1;
8 = (
"0.2226092",
"-0.5721548",
"-0.7796207"
);
9 = 275;
};
"{TIFF}" = {
DateTime = "2015:04:01 10:33:37";
Make = Apple;
Model = "iPhone 6";
Software = "8.1.2";
XResolution = 72;
YResolution = 72;
};
}
Is the data I'm looking for within another NSDictionary named Exif? And if so, how do I access it?
#david strauss can you try this once
- (void) saveImage:(UIImage *)imageToSave withInfo:(NSDictionary *)info{
// Get the assets library
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Get the image metadata (EXIF & TIFF)
NSMutableDictionary * imageMetadata = [[info objectForKey:UIImagePickerControllerMediaMetadata] mutableCopy];
// add GPS data
CLLocation * loc = <•••>; // need a location here
if ( loc ) {
[imageMetadata setObject:[self gpsDictionaryForLocation:loc] forKey:(NSString*)kCGImagePropertyGPSDictionary];
}
ALAssetsLibraryWriteImageCompletionBlock imageWriteCompletionBlock =
^(NSURL *newURL, NSError *error) {
if (error) {
NSLog( #"Error writing image with metadata to Photo Library: %#", error );
} else {
NSLog( #"Wrote image %# with metadata %# to Photo Library",newURL,imageMetadata);
}
};
// Save the new image to the Camera Roll
[library writeImageToSavedPhotosAlbum:[imageToSave CGImage]
metadata:imageMetadata
completionBlock:imageWriteCompletionBlock];
[imageMetadata release];
[library release];
}
The metadata dictionary as you've noticed consists of several dictionaries.
So to answer your question - yes, if you're looking for specific values you can access the inner dictionaries. Also, you'd better use the proper keys from ImageIO constants; for example:
NSLog(#"%#", imageMetadata[(NSString*)kCGImagePropertyExifDictionary][(NSString*)kCGImagePropertyExifISOSpeedRatings]);
Or, you can use a key-path:
NSString *keyPath = [NSString stringWithFormat:#"%#.%#",
(NSString*)kCGImagePropertyExifDictionary, (NSString*)kCGImagePropertyExifISOSpeedRatings];
NSLog(#"%#", [imageMetadata valueForKeyPath:keyPath]);
your all required data is within this dictionary only.
you can use json formatter to see the exact location of your data.
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: imageMetadata
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
}
after this get the exact location of your data from json

iOS geocoding data from google parsing json

I'm pulling some data from google maps but I can't seem to do anything with it. Here's my code:
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
//do something with the data!
NSError *e = nil;
//parse the json data
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: receivedData options: NSJSONReadingMutableContainers error: &e];
//get the lat and long and put it into an array
locationData = [[NSMutableArray alloc] init];
NSLog(#"%#", [jsonArray objectAtIndex:0]);
}
if I log jsonArray.count I get 2, which seems right since google will return results and status at the top level. But if I try to get object 0 it crashes. If I try to do something like this it also crashes:
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
//do something with the data!
NSError *e = nil;
//parse the json data
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: receivedData options: NSJSONReadingMutableContainers error: &e];
//get the lat and long and put it into an array
locationData = [[NSMutableArray alloc] init];
for(NSDictionary* thisLocationDict in jsonArray) {
NSString* location = [thisLocationDict objectForKey:#"results"];
[locationData addObject:location];
}
}
I use this code to get data from Twitter with no problems. The error I get in the console is I am trying to get an object of a string:
-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x798a270
Here's the json google is sending me:
results = (
{
"address_components" = (
{
"long_name" = 2900;
"short_name" = 2900;
types = (
"street_number"
);
},
{
"long_name" = "Horizon Dr";
"short_name" = "Horizon Dr";
types = (
route
);
},
{
"long_name" = "King of Prussia";
"short_name" = "King of Prussia";
types = (
locality,
political
);
},
{
"long_name" = "Upper Merion";
"short_name" = "Upper Merion";
types = (
"administrative_area_level_3",
political
);
},
{
"long_name" = Montgomery;
"short_name" = Montgomery;
types = (
"administrative_area_level_2",
political
);
},
{
"long_name" = Pennsylvania;
"short_name" = PA;
types = (
"administrative_area_level_1",
political
);
},
{
"long_name" = "United States";
"short_name" = US;
types = (
country,
political
);
},
{
"long_name" = 19406;
"short_name" = 19406;
types = (
"postal_code"
);
}
);
"formatted_address" = "2900 Horizon Dr, King of Prussia, PA 19406, USA";
geometry = {
location = {
lat = "40.0896985";
lng = "-75.341717";
};
"location_type" = ROOFTOP;
viewport = {
northeast = {
lat = "40.09104748029149";
lng = "-75.34036801970849";
};
southwest = {
lat = "40.0883495197085";
lng = "-75.34306598029151";
};
};
};
types = (
"street_address"
);
}
);
status = OK;
}
and the url I am passing:
http://maps.googleapis.com/maps/api/geocode/json?address=2900+Horizon+Drive+King+of+Prussia+,+PA&sensor=false
any idea what I am doing wrong?
The difference from the data that you get from google is that it comes separate by keys, such as results, geometry, formatted_address...
You should do something like this:
NSError *error;
NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&components=country:AU&sensor=false", self.searchBar.text];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.locationArray = [[jsonDict valueForKey:#"results"] valueForKey:#"formatted_address"];
int total = self.locationArray.count;
NSLog(#"locationArray count: %d", self.locationArray.count);
for (int i = 0; i < total; i++)
{
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
NSLog(#"Address: %#", [self.locationArray objectAtIndex:i]);
}

Resources