SocketException: Connection failed (OS Error: Operation not permitted, errno = 1)

2024-06-05
#flutter

Recently, i used flutter to build a macOS app. For some reasons, the data required by application need to fetch from internet. Thus, i chose the Dio package for this purpose. However, something strange happened: when the application called the api, it just raised:

flutter: SocketException: Connection failed (OS Error: Operation not permitted, errno = 1), address = example.com, port = 443

What caused the problem?

According to the Build macOS app section of flutter document, macOS builds are configured by default to be signed, and sandboxed with App Sandbox. It means if we want to confer specific capabilities or services on our macOS app (accessing the internet, accessing files and etc.), we're supposed to set up specific entitlements

Setting up entitlements

Normally, the entitlements files are found in the macos/Runner/ directory. There're two entitlements files: one for debug and the other is for release.

flutter-macos-entitlements

Now, let's config our entitlements, add the com.apple.security.network.client entitlement.

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">  
<plist version="1.0">  
<dict>
    <key>com.apple.security.network.client</key>  
    <true/>  
</dict>  
</plist>

Then restart our application, everything goes well. For more information on this topics, you can see App Sandbox and Entitlements on the Apple Developer site.