gpt4 book ai didi

带有基本身份验证的 iOS swift Web 服务调用

转载 作者:行者123 更新时间:2023-11-30 12:28:17 24 4
gpt4 key购买 nike

我疯狂地尝试从网络服务获取一些数据(JSON)。

有人可以告诉我如何在此通话中添加用户名和密码身份验证吗?一定不能像下面的代码那样。如果您有一些适用于 swift 3.0 的代码,我很乐意看到它。

func downloadData()
{
let url = NSURL(string: "https://www.someurl.com")
let request = NSMutableURLRequest(url: url! as URL)

let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
guard error == nil && data != nil else
{
print("Error:",error!)
return
}

let httpStatus = response as? HTTPURLResponse

if httpStatus!.statusCode == 200
{
if data?.count != 0
{
let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary //because JSON data started with dictionary. Not an array
let status = responseString["status"] as! String

if status == "ok"
{
print("Status is :", status)

//Ok, so far so good. Now let's get the data...
}
else
{
print("Status is not Okay!")
}
}
else
{
print("No data got from url!")
}
}
else
{
print("error httpstatus code is :",httpStatus!.statusCode)
}
}
task.resume()
}

最佳答案

这取决于您的网络服务,但您需要将这些值添加到您的请求中。

例如,向 header 添加值:

let request = NSMutableURLRequest(url: url! as URL)
request.addValue("An_Authentication_String", forHTTPHeaderField: "MyField")

或者您可能需要向您的请求添加正文:How to make HTTP Post request with JSON body in Swift

关于带有基本身份验证的 iOS swift Web 服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43902703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com