我正在向我的移动应用程序调用我自己的 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/