Как совершать сетевые звонки с Siri Intent Extension? - PullRequest
0 голосов
/ 15 октября 2019

Я пытаюсь интегрировать Siri из моего приложения. На самом деле мое требование - сделать UDP-вызов с моим сервером, но, поскольку этого не произошло, я попытался выполнить простой сетевой вызов с URLSession и URLRequest. Для тестирования я пытаюсь зайти на google.com и распечатать ответ, но восстановленный data из обработчика завершения не конвертируется в String и возвращает ноль. Что-нибудь, что мне нужно добавить, либо в файле Info.plist, либо в других местах, чтобы сетевые вызовы были успешными в Intent Extension?

В официальной документации также нет упоминания об этом. Код, который я использую, на самом деле прост, но все же я вставляю его ниже:

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))

здесь ответ всегда nil, хотя statusCode равен 200.

1 Ответ

0 голосов
/ 15 октября 2019

В вашем коде нет ничего плохого. Не все данные могут быть преобразованы в строку. Вы можете прочитать больше об этом в этом ответе . Простое нажатие https://www.google.com/ не возвращает строку. Однако, если вы действительно хотите напечатать строку данных из https://www.google.com/, просто используйте print(tcpData!.base64EncodedString()), и вы получите что-то вроде: PCFkb2N0eXBlIGh0bWw+PGh0bWwgaXRlbXNjb3BlPSIiIGl0ZW10eXBlPSJodHRwOi8vc....

Переключите этот URL на открытый API, такой как SpaceX API , и вы получите правильную строку.

{
  "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
}

Также вы можете остановить принудительное развертывание и вместо этого использовать if let или 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))
...