1

I am trying to integrate Siri from my app. Actually my requirement is do some UDP call with my server but as it was not happening I tried with simple network call with URLSession and URLRequest. For testing I am trying to visit google.com and print the response, but the retured data from the completion handler is not convertible to String and is returning nil. Is the anything I need to add extra either in the Info.plist file or in other places to make the network calls succeed in Intent Extension ?

In the official documentation also there is no mention of this. The code I am using is simple actually but still I am pasting that below:

let session = URLSession.shared
let task = session.dataTask(with: URLRequest(url: URL(string: "https://www.google.com/")!), completionHandler: { (tcpData, response, error) in
    if error != nil {
        print("tcp error \(error!.localizedDescription)")
    }
    if let res = response as? HTTPURLResponse {
        print(res.statusCode)
    }
    if tcpData != nil {
        print(String(data: tcpData!, encoding: String.Encoding.utf8) ?? "N/A")
    }
})

task.resume()
completion(TurnOnNodeAppIntentResponse.init(code: TurnOnNodeAppIntentResponseCode.success, userActivity: nil))

here is the response is always nil though statusCode is 200.

DoesData
  • 6,594
  • 3
  • 39
  • 62
Anuran Barman
  • 1,556
  • 2
  • 16
  • 31

1 Answers1

0

There is nothing wrong with your code. Not all data can be converted to a String. You can read more about that in this answer. Just hitting https://www.google.com/ doesn't return a string. However, if you really want to print the a string of the data from https://www.google.com/ just use print(tcpData!.base64EncodedString()) and you'll get something like: PCFkb2N0eXBlIGh0bWw+PGh0bWwgaXRlbXNjb3BlPSIiIGl0ZW10eXBlPSJodHRwOi8vc....

Switch that URL to an open API like the SpaceX API and you'll get a valid string.

{
  "flight_number": 83,
  "mission_name": "Amos-17",
  "mission_id": [

  ],
  "launch_year": "2019",
  "launch_date_unix": 1565131920,
  "launch_date_utc": "2019-08-06T22:52:00.000Z",
  "launch_date_local": "2019-08-06T18:52:00-04:00",
  "is_tentative": false,
  "tentative_max_precision": "hour",
  "tbd": false,
  "launch_window": 5280,
  "rocket": {
    "rocket_id": "falcon9",
    "rocket_name": "Falcon 9",
    "rocket_type": "FT",
    "first_stage": {
      "cores": [
        {
          "core_serial": "B1047",
          "flight": 3,
          "block": 5,
          "gridfins": false,
          "legs": false,
          "reused": true,
          "land_success": null,
          "landing_intent": false,
          "landing_type": null,
          "landing_vehicle": null
        }
      ]
    },
    "second_stage": {
      "block": 5,
      "payloads": [
        {
          "payload_id": "Amos-17",
          "norad_id": [

          ],
          "reused": false,
          "customers": [
            "Spacecom"
          ],
          "nationality": "Israel",
          "manufacturer": "Boeing Satellite Systems",
          "payload_type": "Satellite",
          "payload_mass_kg": 6500,
          "payload_mass_lbs": 14330.05,
          "orbit": "GTO",
          "orbit_params": {
            "reference_system": "geocentric",
            "regime": "geostationary",
            "longitude": 17,
            "semi_major_axis_km": null,
            "eccentricity": null,
            "periapsis_km": null,
            "apoapsis_km": null,
            "inclination_deg": null,
            "period_min": null,
            "lifespan_years": 15,
            "epoch": null,
            "mean_motion": null,
            "raan": null,
            "arg_of_pericenter": null,
            "mean_anomaly": null
          },
          "uid": "UerI6qmZTU2Fx2efDFm3QQ=="
        }
      ]
    },
    "fairings": {
      "reused": false,
      "recovery_attempt": true,
      "recovered": true,
      "ship": "GOMSTREE"
    }
  },
  "ships": [
    "GOMSTREE",
    "GONAVIGATOR"
  ],
  "telemetry": {
    "flight_club": null
  },
  "launch_site": {
    "site_id": "ccafs_slc_40",
    "site_name": "CCAFS SLC 40",
    "site_name_long": "Cape Canaveral Air Force Station Space Launch Complex 40"
  },
  "launch_success": true,
  "links": {
    "mission_patch": "https://images2.imgbox.com/a0/ab/XUoByiuR_o.png",
    "mission_patch_small": "https://images2.imgbox.com/f1/4a/WAkSmKfY_o.png",
    "reddit_campaign": "https://www.reddit.com/r/spacex/comments/cjaawx/amos17_launch_campaign_thread",
    "reddit_launch": "https://www.reddit.com/r/spacex/comments/cmedgn/rspacex_amos17_official_launch_discussion_updates",
    "reddit_recovery": null,
    "reddit_media": "https://www.reddit.com/r/spacex/comments/cmppne/rspacex_amos17_media_thread_videos_images_gifs",
    "presskit": "https://www.spacex.com/sites/spacex/files/amos-17_mission_press_kit_8_6_2019.pdf",
    "article_link": "https://spaceflightnow.com/2019/08/07/spacex-launches-israeli-owned-telecom-satellite/",
    "wikipedia": "https://en.wikipedia.org/wiki/Spacecom",
    "video_link": "https://youtu.be/fZh82-WcCuo",
    "youtube_id": "fZh82-WcCuo",
    "flickr_images": [
      "https://live.staticflickr.com/65535/48478269312_58dd3dc446_o.jpg",
      "https://live.staticflickr.com/65535/48478269747_353dcb2e62_o.jpg",
      "https://live.staticflickr.com/65535/48478119901_2de0441026_o.jpg",
      "https://live.staticflickr.com/65535/48478120646_ab72c2c6c3_o.jpg",
      "https://live.staticflickr.com/65535/48478120031_5aae1f6131_o.jpg",
      "https://live.staticflickr.com/65535/48478269442_08479bed36_o.jpg"
    ]
  },
  "details": "SpaceX will launch Boeing built Amos-17, a geostationary communications satellite for Israeli company Spacecom. The satellite will be delivered to GTO from KSC LC-39A or possibly CCAFS SLC-40, and will replace the defunct Amos-5 at 17° E. Amos-17 carries multi-band high throughput and regional beams servicing Africa, Europe and the Middle East. The cost of this launch is covered for Spacecom by SpaceX credit following the Amos-6 incident. A recovery of the booster for this mission is not expected.",
  "upcoming": false,
  "static_fire_date_utc": "2019-08-01T00:00:00.000Z",
  "static_fire_date_unix": 1564617600,
  "timeline": null,
  "crew": null
}

Also you might want to stop force unwrapping and instead use if let or guard

let session = URLSession.shared
let task = session.dataTask(with: URLRequest(url: URL(string: "https://api.spacexdata.com/v3/launches/latest")!), completionHandler: { (tcpData, response, error) in
    if let err = error {
        print("tcp error \(err.localizedDescription)")
    }

    if let res = response as? HTTPURLResponse {
        print(res.statusCode)
    }

    if let data = tcpData {
        print(String(data: data, encoding: String.Encoding.utf8) ?? "N/A")
    }
})

task.resume()
completion(TurnOnNodeAppIntentResponse.init(code: TurnOnNodeAppIntentResponseCode.success, userActivity: nil))
DoesData
  • 6,594
  • 3
  • 39
  • 62
  • So there is no extra work that needs to be done for Siri Intent Extension target ? Nothing Like 'Background Modes' from capabilities of the target ? Network calling will work out of the box for intent extension? – Anuran Barman Oct 15 '19 at 12:14
  • Your request is already going through it just isn't returning string data. Use `print(tcpData!.base64EncodedString())` to see the data response. You might want to enable background fetch for good measure though. – DoesData Oct 15 '19 at 12:25