Short answer

A photo can carry its location in two places. Setting location on a Photos creation request, as the 2018 code did, stores it in the user's Photos library. To put it inside the image file itself, write a GPS dictionary (kCGImagePropertyGPSDictionary) with ImageIO, then save that data with PHAssetCreationRequest.addResource(with:data:options:). EXIF stores latitude and longitude as positive numbers plus an N/S and E/W letter, so code that reads the numbers without the letters puts Jakarta about 1,366 km away, north of the equator.

SWIFT TIPS · UIKIT · PHOTOS · IMAGEIO

First posted on September 7, 2018 for Swift 4, as "CLLocation Tag Image GeoLocation in IPhone Swift 4". Rewritten on November 18, 2026. The GPS tagging was run on a Mac with ImageIO on a small image made in memory and a fixed sample coordinate, with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. Nothing was saved to a Photos library and no real location was read. The Photos code was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 and iOS 26.2 as deployment targets, but not run on a device.

In 2018 I wanted to save a picture with the place it was taken. The post asked for location permission, started location updates, and passed the location manager's current location to a function that created a photo in the Photos library with PHAssetChangeRequest.creationRequestForAsset(from:) and set the request's location. The post noted that this location could be read in Photos on the Mac and the iPhone, but wasn't written into the file's EXIF metadata.

That note was accurate, and it's the key to this topic. This rewrite shows how to write the location into the file too, what the GPS data looks like inside it, and the mistake to avoid when reading it back.

What goes into the file

I made a small gray JPEG in memory and tagged it with a fixed coordinate in central Jakarta, -6.1754, 106.8272, first by writing the signed numbers straight in, then with the helper below. Then I read the GPS data back:

Sample JPEG: 723 bytes, GPS: no GPS block
1. Negative latitude, no Ref:  Lat 6.1754, LatRef S, Lon 106.8272, LonRef E
   ImageIO stored the size of the number and turned the minus sign into Ref S.
2. GeoTag.jpeg:  Lat 6.1754, LatRef S, Lon 106.8272, LonRef E
   altitude 8 m, date 2026:11:18 03:00:00 UTC
   read back as -6.1754, 106.8272
3. Reading Latitude and Longitude without the Ref letters: 6.1754, 106.8272
   that point is 1366 km from the real one
  • EXIF has no negative coordinates. The GPS block stores 6.1754 with the letter S, and 106.8272 with E. On this Mac, ImageIO even converted the signed number I passed into that form by itself.
  • The letters matter when reading. A reader that takes only the Latitude and Longitude numbers gets 6.1754, 106.8272, a point north of the equator about 1,366 km from the real one. GeoTag.coordinate(in:) applies the letters and gets -6.1754 back.
  • The rest of the block. The helper also writes the altitude, and the date and time in UTC, which is how EXIF expects GPS time.

Writing GPS data with ImageIO

import Foundation
import ImageIO
import UniformTypeIdentifiers
import CoreLocation

enum GeoTag {
    /// EXIF GPS values are always positive. The hemisphere goes in a separate "Ref" letter.
    static func gpsDictionary(for location: CLLocation) -> [CFString: Any] {
        let c = location.coordinate
        var gps: [CFString: Any] = [
            kCGImagePropertyGPSLatitude: abs(c.latitude),
            kCGImagePropertyGPSLatitudeRef: c.latitude < 0 ? "S" : "N",
            kCGImagePropertyGPSLongitude: abs(c.longitude),
            kCGImagePropertyGPSLongitudeRef: c.longitude < 0 ? "W" : "E",
        ]
        if location.verticalAccuracy >= 0 {
            gps[kCGImagePropertyGPSAltitude] = abs(location.altitude)
            gps[kCGImagePropertyGPSAltitudeRef] = location.altitude < 0 ? 1 : 0
        }
        let utc = TimeZone(identifier: "UTC")!
        let date = DateFormatter(), time = DateFormatter()
        for (f, format) in [(date, "yyyy:MM:dd"), (time, "HH:mm:ss")] {
            f.locale = Locale(identifier: "en_US_POSIX")
            f.timeZone = utc
            f.dateFormat = format
        }
        gps[kCGImagePropertyGPSDateStamp] = date.string(from: location.timestamp)
        gps[kCGImagePropertyGPSTimeStamp] = time.string(from: location.timestamp)
        return gps
    }

    /// Re-encodes JPEG data with a GPS block added. Returns nil if the data isn't an image.
    static func jpeg(_ imageData: Data, adding location: CLLocation, quality: Double = 0.9) -> Data? {
        guard let source = CGImageSourceCreateWithData(imageData as CFData, nil),
              let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { return nil }
        var properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] ?? [:]
        properties[kCGImagePropertyGPSDictionary] = gpsDictionary(for: location)
        properties[kCGImageDestinationLossyCompressionQuality] = quality

        let output = NSMutableData()
        guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else { return nil }
        CGImageDestinationAddImage(destination, image, properties as CFDictionary)
        guard CGImageDestinationFinalize(destination) else { return nil }
        return output as Data
    }

    /// Reads the coordinate back, applying the Ref letters.
    static func coordinate(in imageData: Data) -> CLLocationCoordinate2D? {
        guard let source = CGImageSourceCreateWithData(imageData as CFData, nil),
              let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
              let gps = properties[kCGImagePropertyGPSDictionary] as? [CFString: Any],
              let lat = gps[kCGImagePropertyGPSLatitude] as? Double,
              let lon = gps[kCGImagePropertyGPSLongitude] as? Double else { return nil }
        let south = (gps[kCGImagePropertyGPSLatitudeRef] as? String) == "S"
        let west = (gps[kCGImagePropertyGPSLongitudeRef] as? String) == "W"
        return CLLocationCoordinate2D(latitude: south ? -lat : lat, longitude: west ? -lon : lon)
    }
}

Saving it to Photos

import UIKit
import Photos
import CoreLocation

enum PhotoSaver {
    enum SaveError: LocalizedError {
        case notAllowed, notAnImage
        var errorDescription: String? {
            switch self {
            case .notAllowed: return "Allow adding photos in Settings to save this picture."
            case .notAnImage: return "The picture couldn't be encoded."
            }
        }
    }

    /// Saves a photo with its location two ways: as GPS EXIF inside the JPEG file,
    /// and as the asset's location in the Photos library.
    /// Needs NSPhotoLibraryAddUsageDescription in Info.plist.
    static func save(_ image: UIImage, at location: CLLocation) async throws {
        let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
        guard status == .authorized || status == .limited else { throw SaveError.notAllowed }
        guard let plain = image.jpegData(compressionQuality: 0.9),
              let tagged = GeoTag.jpeg(plain, adding: location) else { throw SaveError.notAnImage }

        try await PHPhotoLibrary.shared().performChanges {
            let request = PHAssetCreationRequest.forAsset()
            request.addResource(with: .photo, data: tagged, options: nil)
            request.location = location
            request.creationDate = location.timestamp
        }
    }
}

How it works

  • Both places get the location. addResource(with: .photo, data:) saves the tagged JPEG data as the photo, so the GPS block is part of the file. request.location sets the asset's location in the Photos library, which is what the 2018 code did.
  • Add-only permission. requestAuthorization(for: .addOnly) asks only to add photos, not to read the library, and needs NSPhotoLibraryAddUsageDescription in Info.plist.
  • The original metadata is kept. GeoTag.jpeg copies the image's existing properties and adds the GPS block to them, so orientation and other tags survive.
  • Accuracy check. Altitude is only written when verticalAccuracy is zero or more. Core Location uses a negative value to say the altitude isn't valid.

Getting the location first

The 2018 code read locManager.location right after calling requestAlwaysAuthorization() and startUpdatingLocation() in viewDidLoad. At that moment the user hasn't answered the permission prompt and no fix has arrived, so the location is usually nil. It also asked for "Always" permission, which a camera feature doesn't need. Ask for "When In Use", wait for the delegate to deliver a location, and only then save. The Core Location post linked below shows that flow step by step.

Also think about whether the location should go into the file at all. A photo with GPS data tells everyone who gets the file where it was taken. If you set only the Photos library location, as the 2018 code did, the JPEG data your app saves doesn't contain it.

A quick check for your project

  1. Search for kCGImagePropertyGPSLatitude in code that reads images and check that it also reads kCGImagePropertyGPSLatitudeRef.
  2. Search for requestAlwaysAuthorization and ask whether the feature needs it.
  3. Search for locationManager.location read right after a permission request. That value is usually still nil.

What the 2018 version said

The original imported MobileCoreServices and ImageIO without using them, and passed imageCoordinate.image!, a name the class didn't declare (its outlet was imageView). Type-checked today:

Swift 5 mode: o056_2018.swift:17:25: error: cannot find 'imageCoordinate' in scope
Swift 6 mode: o056_2018.swift:17:25: error: cannot find 'imageCoordinate' in scope

Sources