swift - 向我的移动应用程序调用我自己的 API

标签 swift xcode postman

我正在向我的移动应用程序调用我自己的 API,并将移动应用程序中的值发布到我的 API,但它不起作用。这是我的代码,调用 API 来获取值并将值发布到我的 API here is the statement of problem即使该值无法存储到我自己的 API 中,我的移动应用程序仍然能够运行。

let headers = [
      "Content-Type": "application/json",
      "cache-control": "no-cache",
      "Postman-Token": "b839d806-4bd2-4247-9451-1d006a076bf4"
    ]
    let parameters = [
      "name": name,
      "icNumber": icNumber,
      "medicineType": medicineType,
      "amount": amount
    ] as [String : Any]

    do {
        let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])

       let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:8080/post")! as URL,
                                               cachePolicy: .useProtocolCachePolicy,
                                           timeoutInterval: 10.0)
       request.httpMethod = "POST"
       request.allHTTPHeaderFields = headers
       request.httpBody = postData as Data

        print("post ")

       let session = URLSession.shared
       let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
         if (error != nil) {
            print(error as Any)
         } else {
           let httpResponse = response as? HTTPURLResponse
            print(httpResponse as Any)
         }
       })

       dataTask.resume()
    } catch {
        print(error)
    }

最佳答案

由于您的 API 是通过非安全协议(protocol) (http) 提供的,因此 iOS 将阻止对其进行任何调用,您需要确保其安全 (https),​​或者出于开发目的添加异常(exception)。

要为特定域添加异常(exception),请在应用程序的 info.plist 中添加以下内容:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <false/>
  <key>NSExceptionDomains</key>
  <dict>
    <key>your-domain-here.com</key>
    <dict>
      <key>NSIncludesSubdomains</key>
      <true/>
      <key>NSExceptionAllowsInsecureHTTPLoads</key>
      <true/>
    </dict>
  </dict>
</dict>

your-domain-here.com 替换为您的域名。

关于swift - 向我的移动应用程序调用我自己的 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58310536/

相关文章:

iphone - dismissModalViewController 与 iAds。横幅 View 有广告但可能被遮挡

iphone - 在代码 xcode iOS objective c 中禁用 DLogs

java - 如何在 postman 中将对象的ArrayList转换为json格式

arrays - 使用 Swift 将声音文件推送到数组

swift - 如何使用新的 Firebase 快速更新电子邮件和密码

swift - Facebook-IOS-SDK pod 安装问题

xcode - Firemonkey App 无法上传到 Mac App Store

c# asp.net core Bearer错误="invalid_token"

javascript - 从外部文件在 postman 中加载 json 模式

swift - 如何在 Reactive Extensions 中组合两个 observables 以便对结果进行分页?