Someone shares a holiday photo with “Remove location” turned on. If the recipient opens the file in a metadata viewer, what will they find?
Location Intelligence, part 2 of 4.
Both features look like small conveniences. Underneath are four separate questions the implementation has to answer. What metadata did the app actually receive? How much should it be trusted? Which permission path delivered it? And what, exactly, is in the bytes that leave the device when the photo is shared?
Some photos carry a location, some do not, and some carry one that was edited after capture. A good implementation keeps those cases distinct from import to export. The second feature, the switch, is a privacy promise, and I will argue it should be verified against the output file every time.
The library, the file, and the picker are three sources
There are three common ways a photo's location reaches an app, and they do not always agree.
A PHAsset exposes a location property for assets the app is authorized to read. That value comes from the Photos library's database, and it reflects any adjustment the user made in the Photos app.
An image file can contain GPS tags in its embedded metadata, which Image I/O reads. That is what the camera wrote at capture, unless the file has been re-exported since.
The system photo picker hands the app a copy of what the person chose. It runs out of process, needs no library permission, and lets the person decide whether location is included in what is shared. The representation the app receives may therefore have different metadata from the original in the library.
Two assumptions cause most of the trouble. Receiving an image does not mean the app has access to the photo library. Receiving pixels does not mean the app received a location. Treat whatever representation arrived as the input, and if a feature needs more, request it through a flow that explains why.
Keep provenance before choosing a coordinate
Since sources can disagree, the model records where each value came from:
import Foundation
struct PhotoLocationEvidence: Equatable, Sendable {
enum Source: String, Sendable {
case photoLibrary
case embeddedMetadata
case userAssigned
}
let latitude: Double
let longitude: Double
let source: Source
}
enum PhotoLocationResolution: Equatable, Sendable {
case absent
case available(PhotoLocationEvidence)
case needsReview([PhotoLocationEvidence])
}
func resolveLocation(
from evidence: [PhotoLocationEvidence],
agreementMeters: Double = 250
) -> PhotoLocationResolution {
if let assigned = evidence.last(where: { $0.source == .userAssigned }) {
return .available(assigned)
}
guard let first = evidence.first else { return .absent }
let allAgree = evidence.dropFirst().allSatisfy {
approximateDistanceMeters(first, $0) <= agreementMeters
}
return allAgree ? .available(first) : .needsReview(evidence)
}
func approximateDistanceMeters(
_ a: PhotoLocationEvidence, _ b: PhotoLocationEvidence
) -> Double {
let metersPerDegree = 111_195.0
let meanLatitude = (a.latitude + b.latitude) / 2 * .pi / 180
var deltaLongitude = abs(a.longitude - b.longitude)
if deltaLongitude > 180 { deltaLongitude = 360 - deltaLongitude }
let north = (a.latitude - b.latitude) * metersPerDegree
let east = deltaLongitude * metersPerDegree * cos(meanLatitude)
return (north * north + east * east).squareRoot()
}The resolver states a policy. An explicit choice by the user inside this app wins. Otherwise, sources that agree within a tolerance produce one answer, and sources that disagree produce .needsReview with all of the evidence attached. It never picks a winner silently, because no source is always the more accurate one: the library value may be a deliberate correction, or a mistake made while tidying an album.
The distance function is a short-range approximation, sufficient for asking whether two readings are within a few hundred meters of each other, and it accounts for the antimeridian. It is not meant for navigation.
One distinction is worth protecting in the data model: "show this photo at this place" and "the camera was at this place" are different statements. A user who drags a photo to the right beach in your app has made the first. That should not rewrite the original file, and it should not erase the record of what the file said.
Decode GPS metadata defensively
EXIF GPS data is structured input from an arbitrary source. Treat it like a network payload.
import ImageIO
enum GPSReading: Equatable, Sendable {
case absent
case malformed
case coordinate(latitude: Double, longitude: Double)
}
func gpsReading(from properties: [CFString: Any]) -> GPSReading {
guard let gps = properties[kCGImagePropertyGPSDictionary] as? [CFString: Any] else {
return .absent
}
guard let latitude = gps[kCGImagePropertyGPSLatitude] as? Double,
let longitude = gps[kCGImagePropertyGPSLongitude] as? Double,
let latitudeRef = gps[kCGImagePropertyGPSLatitudeRef] as? String,
let longitudeRef = gps[kCGImagePropertyGPSLongitudeRef] as? String,
latitude.isFinite, longitude.isFinite,
(0...90).contains(latitude),
(0...180).contains(longitude) else {
return .malformed
}
let latitudeSign: Double
switch latitudeRef {
case "N": latitudeSign = 1
case "S": latitudeSign = -1
default: return .malformed
}
let longitudeSign: Double
switch longitudeRef {
case "E": longitudeSign = 1
case "W": longitudeSign = -1
default: return .malformed
}
return .coordinate(
latitude: latitude * latitudeSign,
longitude: longitude * longitudeSign
)
}
func imageProperties(at url: URL) -> [CFString: Any]? {
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else {
return nil
}
return CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
}EXIF stores latitude and longitude as unsigned magnitudes with a separate hemisphere reference. The most common parsing bug is ignoring the reference, which moves every photo from Sydney to the North Pacific and every photo from New York to Central Asia. The second is defaulting a missing reference to north and east instead of rejecting the record.
The result has three cases on purpose. .absent and .malformed lead to different behavior: the first is normal, the second is worth counting in diagnostics, and neither should ever become (0, 0). Zero latitude, zero longitude is a real point in the Gulf of Guinea, and any app that uses it as "unknown" eventually draws a cluster of photos there.
Timestamps need the same suspicion. The classic EXIF capture time is a local wall-clock string with no time zone; newer files may add an offset tag, and many do not. A file's modification date, the library's creation date, and the embedded capture time can describe three different events. A travel timeline built by sorting whichever date was easiest to read will interleave two cities incorrectly as soon as the trip crosses a time zone. Record which source and which zone assumption produced each timestamp.
Missing location is a normal result
A photo can lack location because the camera had no fix, because the user turned location off for the Camera app, because a messaging app stripped it, because the picker was asked not to include it, or because it is a screenshot. None of these is an error, and none is fixed by asking for broader permissions.
Offer manual placement where it helps, and store the result as .userAssigned.
Resist one shortcut: filling a missing capture location with the device's current location at import time. That converts "imported here" into "photographed here", and it does so in a field nobody will question later. If the import location is useful, store it under its own name.
Metadata is a claim
Embedded coordinates can be edited with freely available tools, and the Photos app itself lets anyone adjust a photo's location. For a travel journal this is a feature. For attendance, expense claims, insurance evidence, or access control, a photo's coordinates alone are not proof that anyone was anywhere.
The wording in the product should match. "Location attached to this photo" is accurate. "Verified capture location" asserts something the app has no means of knowing. The difference is two words in a label and a great deal in what the product is vouching for.
Export privacy is a property of the output bytes
Now the switch. "Remove location" is a statement about a file that leaves the device. Removing a key from a metadata dictionary in memory proves nothing about that file. Location can survive in:
- XMP, a second metadata block that often duplicates EXIF;
- a maker note the code never parsed;
- the video half of a Live Photo;
- a sidecar file;
- the original asset, if the share path quietly falls back to it;
- the pixels.
The design I trust has three properties. It builds a new image from decoded pixels, so nothing is carried across by default. It writes only the metadata it explicitly lists. And it reopens the file it produced and checks.
import UniformTypeIdentifiers
enum ExportError: Error, Equatable {
case unreadableSource
case encodingFailed
case unverifiable
case locationStillPresent
}
func containsLocationMetadata(at url: URL) -> Bool? {
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil)
as? [CFString: Any] else {
return nil
}
if properties[kCGImagePropertyGPSDictionary] != nil { return true }
guard let metadata = CGImageSourceCopyMetadataAtIndex(source, 0, nil),
let tags = CGImageMetadataCopyTags(metadata) as? [CGImageMetadataTag] else {
return false
}
return tags.contains { tag in
let name = (CGImageMetadataTagCopyName(tag) as String?) ?? ""
return name.uppercased().hasPrefix("GPS")
}
}
func exportDerivativeWithoutLocation(
from sourceURL: URL,
to destinationURL: URL,
maxPixelSize: Int,
quality: Double = 0.85
) throws(ExportError) {
guard let source = CGImageSourceCreateWithURL(sourceURL as CFURL, nil) else {
throw .unreadableSource
}
let decodeOptions: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize
]
guard let pixels = CGImageSourceCreateThumbnailAtIndex(
source, 0, decodeOptions as CFDictionary
) else {
throw .unreadableSource
}
guard let destination = CGImageDestinationCreateWithURL(
destinationURL as CFURL, UTType.jpeg.identifier as CFString, 1, nil
) else {
throw .encodingFailed
}
let allowedProperties: [CFString: Any] = [
kCGImageDestinationLossyCompressionQuality: quality
]
CGImageDestinationAddImage(destination, pixels, allowedProperties as CFDictionary)
guard CGImageDestinationFinalize(destination) else {
throw .encodingFailed
}
switch containsLocationMetadata(at: destinationURL) {
case .some(false):
return
case .some(true):
try? FileManager.default.removeItem(at: destinationURL)
throw .locationStillPresent
case .none:
try? FileManager.default.removeItem(at: destinationURL)
throw .unverifiable
}
}The decode step asks Image I/O for pixels with the orientation transform applied. That matters because orientation is itself metadata: if the tag is dropped and the pixels are not rotated, portrait photos arrive sideways. Baking the rotation into the pixels lets the export discard the tag.
CGImageDestinationAddImage receives a CGImage and a property dictionary. A CGImage carries no EXIF, so the output contains only what allowedProperties lists. The sibling function CGImageDestinationAddImageFromSource copies the source's metadata and then applies your changes on top, which makes it a denylist and leaves you responsible for knowing every place a location can hide. I use the allowlist form for anything described to the user as "removed".
The last step reopens the written file and looks for a GPS dictionary and for GPS tags in XMP. If it finds any, or cannot read the file, the output is deleted and the export fails. A failed export is a much better outcome than a shared file that contradicts the switch. I ran this function against synthetic JPEGs containing GPS tags in both hemispheres; the outputs contained none, and the same check on the inputs reported them present. That is a test of one format on one OS version, which is the reason the verification runs inside the export function on every call and is not left to a unit test alone.
This code is for still images. It does not handle HDR gain maps, wide-color profiles, or quality tuning, and a Live Photo or a video needs its own export path and its own verification. A still-image test tells you nothing about the paired movie file.
Removing metadata does not anonymize a photo
A street sign, a house number, a landmark, a reflection in a window, or a letter on a table can each identify a place or a person. The switch should say what the code does: "Remove embedded location data". Words such as "anonymous" or "private" promise more than metadata removal delivers.
Show a preview generated from the file that will actually be shared, and pass that file's URL to the share sheet. A common regression is a preview built from the cleaned derivative while the share action, after a later refactor, hands over the original PHAsset. A UI test that inspects the shared item catches it.
Make resource cost explicit
Originals are large; a 48-megapixel photo decodes to roughly 190 MB of bitmap. Three rules keep a batch import from being terminated for memory:
- for grid thumbnails, use Image I/O's thumbnail API or PhotoKit's sized requests, and never decode the original;
- process a bounded number of photos at once, and release each decoded image before starting the next;
- cancel remaining work when the user abandons the import.
For iCloud-backed assets, the record can exist locally while the pixels are still in the cloud. Downloading and processing are separate states with separate failure modes, and "could not download right now" should be recoverable without restarting the batch.
Test the representation matrix
Generate fixtures in code so the tests do not depend on anyone's personal photos:
import CoreGraphics
func writeFixtureJPEG(
to url: URL,
gps: [CFString: Any]?
) -> Bool {
guard let context = CGContext(
data: nil, width: 8, height: 8, bitsPerComponent: 8, bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue
), let image = context.makeImage(),
let destination = CGImageDestinationCreateWithURL(
url as CFURL, UTType.jpeg.identifier as CFString, 1, nil
) else {
return false
}
var properties: [CFString: Any] = [:]
if let gps { properties[kCGImagePropertyGPSDictionary] = gps }
CGImageDestinationAddImage(destination, image, properties as CFDictionary)
return CGImageDestinationFinalize(destination)
}With that helper, the matrix is cheap to cover:
- no GPS dictionary:
.absent; - northern and southern, eastern and western hemispheres: correct signs;
- a missing or unknown hemisphere reference:
.malformed; - latitude 91, longitude 181,
NaN:.malformed; - library location and embedded location 5 km apart:
.needsReview; - export, then inspect the output with a second tool such as
exiftoolorsips; - a rotated source: the exported pixels are upright.
Add device tests for the cases a fixture cannot produce: a Live Photo, an asset that is not downloaded while offline, and the exact item handed to the share sheet.
What to ask of your own app
- Which of the three sources does each location value come from, and is that recorded?
- What does the parser return for a missing hemisphere reference?
- Does export copy metadata and remove some of it, or start from pixels and add only what is listed?
- Is the shared file reopened and inspected before it leaves the app?
- Does the UI claim more than "embedded location removed"?
Part 3 turns to location inferred from what the camera sees, where the evidence is a model's guess and the same discipline applies with more force.
References
- Photos: PHAsset.location
- PhotoKit: Selecting photos and videos in iOS
- Image I/O: CGImageSourceCopyPropertiesAtIndex
- Image I/O: CGImageDestinationAddImage
- Image I/O: GPS dictionary keys
Related editions
- Edition 37 · MapKit Is Not Just a Map
- Edition 39 · From Camera Frame to Map Pin
- Edition 36 · A Coordinate Is an Observation, Not the Truth
If this edition sharpened your next review, you can buy me a coffee.