RP89
RP89

Reputation: 121

iOS app crash when fetcing the IP address

In my application, I am suing for getting the IP address. Below is the code for getting IP.

 func getUrlIPAddress(){
      let url = URL(string: "https://api.ipify.org")

     do {
        if let url = url {
            let ipAddress = try String(contentsOf: url)
            self.ipAddressSend = ipAddress
            UserDefaults.standard.set(ipAddress, forKey: "agent_ipaddress")
        }
     } catch let error {
        print(error)
     }
    }

But one crash is reported here in the appstore console.I am not able to reproduce the crash. Even if its handled with try and catch why its crashing ? Here is the crashlog details. enter image description here

Please help me to found the reason for this crash.

Upvotes: 0

Views: 2775

Answers (1)

your code works, but it gives me this compiler warning: "Synchronous URL loading of https://api.ipify.org should not occur on this application's main thread as it may lead to UI unresponsiveness. Please switch to an asynchronous networking API such as URLSession."

You are better of using this approach:

func getUrlIPAddress() {
    let url = URL(string: "https://api.ipify.org")
    do {
        if let url = url {
            Task{@MainActor in
                let (data, _) = try await URLSession.shared.data(from: url)
                let ipAddress = String(data: data, encoding: .utf8)!
                self.ipAddressSend = ipAddress
                UserDefaults.standard.set(ipAddress, forKey: "agent_ipaddress")
            }
        }
    } catch let error {
        print(error)
    }
}

EDIT-1: for ios 12, you could try this:

func getUrlIPAddress() {
    guard let url = URL(string: "https://api.ipify.org") else { return }
    URLSession.shared.dataTask(with: url) { data, _, error in
        guard let data = data else { return }
        let ipAddress = String(data: data, encoding: .utf8)!
        print("\n---> ipAddress: \(ipAddress)")
        self.ipAddressSend = ipAddress
        UserDefaults.standard.set(ipAddress, forKey: "agent_ipaddress")
    }.resume()
}

Upvotes: 2

Related Questions