"finish with error - code: -1022" is URLError.appTransportSecurityRequiresSecureConnection: App Transport Security blocked an http:// address. Use https://, or an exception for that one domain, rather than NSAllowsArbitraryLoads. Then, to show a big remote image in a small view, downsample it with ImageIO's CGImageSourceCreateThumbnailAtIndex. In a test, a 4000 x 3000 photo needed 45.8 MB as a full bitmap and 2.7 MB at the size of a 325-point view on a 3x screen, with its shape kept.
SWIFT TIPS · UIKIT · IMAGES
First posted on September 14, 2018 for Swift 4.2, as "[UIImage] If UIImage Can't Read Use Web API Swift 4.2". Rewritten on November 18, 2026. The tests were run on a Mac with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1, as a Mac Catalyst program (UIKit on macOS, not an iPhone or the simulator), on an image made in memory and against a local test server on 127.0.0.1. Kingfisher wasn't installed or run; what this post says about it comes from its source code. The 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 a remote image wouldn't load, and the debug area said "finish with error - code: -1022". The post's fix had two steps: set Allow Arbitrary Loads to YES under App Transport Security Settings in Info.plist, and load the image with the Kingfisher CocoaPod. A linked Gist showed the Kingfisher call, with a ResizingImageProcessor that resized the image to 325 x 325 points times the screen scale.
The error and the fix belong together. This rewrite explains what -1022 means, points out a typo in the sample address that gives a different error, narrows the plist change, and replaces the resize with one that keeps the image's shape and uses far less memory.
What -1022 means, and what -1002 means
URLError.Code.appTransportSecurityRequiresSecureConnection.rawValue = -1022
URL(string: "hhtp://googleImage.com/find") -> a URL with scheme "hhtp"
Loading it: URLError -1002 (unsupportedURL)
- -1022 is
appTransportSecurityRequiresSecureConnection. Apple's documentation describes it as ATS refusing a connection because it isn't secure, and says ATS requires HTTPS for connections made withURLSession. The address washttp://. - The Gist's sample address starts with
hhtp://, a typo.URL(string:)accepted it, because "hhtp" is a valid scheme name, and loading it failed with -1002,unsupportedURL, which Apple's documentation says typically means there's no protocol handler for the URL. If you see -1002 where you expected -1022, check how the scheme is spelled.
I couldn't make the -1022 itself appear on this Mac. A command-line program loaded a plain http address with no error, with or without an Info.plist built in:
Program without an Info.plist:
http://127.0.0.1:8765/stats: HTTP 200, 47 bytes
Program with an embedded Info.plist and no ATS keys:
http://127.0.0.1:8765/stats: HTTP 200, 47 bytes
So I can't show the error here. Apple describes ATS as a protection for apps and app extensions, and the 2018 error came from an app.
Fix the address first
Try the same address with https://; many image servers already answer on it, and then you need no plist change at all. If the server really only speaks HTTP, add an exception for its domain under NSExceptionDomains instead of turning on NSAllowsArbitraryLoads. Apple's documentation says that key disables ATS for every domain you didn't list, needs a justification during App Store review, and is usually worse than upgrading the server or using a narrower exception. The Kingfisher reload post linked below has the exact plist.
Why not the 2018 resize
Kingfisher's source code, both the current version and version 4.10.1 from the Swift 4 days, shows two things about ResizingImageProcessor:
- It stretches by default. Its
modeparameter defaults to.none, and for.nonethe output size is simply the reference size. The Gist passed only a size, 325 x 325 times the scale, so a 4:3 photo would come out square, squeezed sideways. Passingmode: .aspectFitkeeps the shape. - It works on the decoded image. In the current source, the comment above the type says that to make an image from data smaller,
DownsamplingImageProcessoris more efficient and uses less memory.
The same idea without a library is ImageIO's thumbnail function, which decodes the data straight to the size you ask for.
Downsampling with ImageIO
import UIKit
import ImageIO
enum ImageDownsampler {
/// Decodes image data straight to a bitmap no larger than `pointSize` at `scale`,
/// without first decoding the full-size image. Keeps the aspect ratio.
static func image(from data: Data, fitting pointSize: CGSize, scale: CGFloat) -> UIImage? {
let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
guard let source = CGImageSourceCreateWithData(data as CFData, sourceOptions) else { return nil }
let maxPixels = max(pointSize.width, pointSize.height) * scale
let thumbnailOptions = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true, // decode now, not on the main thread later
kCGImageSourceCreateThumbnailWithTransform: true, // apply the EXIF orientation
kCGImageSourceThumbnailMaxPixelSize: maxPixels,
] as CFDictionary
guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, thumbnailOptions) else { return nil }
return UIImage(cgImage: cgImage, scale: scale, orientation: .up)
}
}
enum ImageLoadError: LocalizedError {
case badStatus(Int)
case notAnImage
var errorDescription: String? {
switch self {
case .badStatus(let code): return "The server answered with status \(code)."
case .notAnImage: return "The data isn't an image this device can read."
}
}
}
/// Loads a remote image and downsamples it for the view that shows it.
struct RemoteImageLoader: Sendable {
var session: URLSession = .shared
func image(at url: URL, fitting pointSize: CGSize, scale: CGFloat) async throws -> UIImage {
let (data, response) = try await session.data(from: url)
if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
throw ImageLoadError.badStatus(http.statusCode)
}
guard let image = ImageDownsampler.image(from: data, fitting: pointSize, scale: scale) else {
throw ImageLoadError.notAnImage
}
return image
}
}
final class ViewPictureViewController: UIViewController {
private let imageView = UIImageView()
private let loader = RemoteImageLoader()
private let imageURL: URL
private var loadTask: Task<Void, Never>?
init(imageURL: URL) {
self.imageURL = imageURL
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
imageView.contentMode = .scaleAspectFit // never stretch
imageView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageView)
NSLayoutConstraint.activate([
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
imageView.widthAnchor.constraint(equalToConstant: 325),
imageView.heightAnchor.constraint(equalToConstant: 325),
])
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard loadTask == nil else { return }
let scale = traitCollection.displayScale
loadTask = Task { [weak self, loader, imageURL] in
do {
let image = try await loader.image(at: imageURL, fitting: CGSize(width: 325, height: 325), scale: scale)
self?.imageView.image = image
} catch let error as URLError where error.code == .cancelled {
} catch {
print("Image failed: \(error.localizedDescription)") // show a placeholder in a real app
}
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isMovingFromParent || isBeingDismissed { loadTask?.cancel() }
}
}
What downsampling saved
I made a 4000 x 3000 JPEG in memory, the size of a phone photo, and compared a plain UIImage(data:) with the downsampler set for a 325 x 325 point view on a 3x screen:
Sample JPEG: 4000 x 3000 px, 228 KB of data
UIImage(data:) bitmap: 4000 x 3000 px, 45.8 MB when decoded
Downsampled for 325 x 325 pt at 3x: 975 x 731 px, 2.7 MB, 325 x 243 pt
Aspect ratio: original 1.333, downsampled 1.334
- The file size says little about memory. The JPEG data was 228 KB. Shown as is, the image needs a 4000 x 3000 bitmap, 45.8 MB. Downsampled for the view, it needed 2.7 MB.
- The shape is kept.
kCGImageSourceThumbnailMaxPixelSizelimits the longer side, here to 975 pixels, and the shorter side follows: 975 x 731, the same 4:3 ratio. In a 325-point square view with.scaleAspectFit, it shows as 325 x 243 points with no stretching. - Decode once, early.
kCGImageSourceShouldCacheImmediatelymakes ImageIO decode while creating the image; Apple's documentation says that by default decoding waits until the image is drawn.kCGImageSourceCreateThumbnailWithTransformapplies the photo's orientation, so a portrait photo isn't shown sideways.
The loader, against the local test server:
Loader /img?mode=etag: image 4 x 4 px
Loader /nope: The server answered with status 404.
Loader /contacts: The data isn't an image this device can read.
A real image loads, a missing one reports the status, and a JSON answer at an image address reports that the data isn't an image instead of failing silently.
How the screen works
- The scale comes from the view. The 2018 Gist used
UIScreen.main.scale.UIScreen.mainis deprecated in iOS 26, and Apple says to use the screen found through context; the code readstraitCollection.displayScaleinstead. - Loading starts in
viewDidAppear, when the trait collection is known, and only once. - Leaving the screen cancels the download.
URLSessionreports that asURLError.cancelled, which thecatchignores.
A quick check for your project
- Search Info.plist for
NSAllowsArbitraryLoadsand your code forhttp://. - Search for
ResizingImageProcessor(without amode:argument; those calls stretch images that aren't the reference shape. - Search for
UIImage(data:on images from a server that you show in small views, such as table cells, and downsample those.
What the 2018 version said
The post showed the Info.plist change in Xcode's property list editor:
![]()
The Gist's view controller set the image in viewDidLoad with imgView.kf.setImage(with:options:) and the resizing processor.
Keep reading on JR Devhub
Comments