复制匹配的信息时出错 - Swift(REST API调用)

问题描述 投票:2回答:1

我正在尝试对通用设备集线器进行REST API调用以打开开关。似乎调用正在进行,但是我收到一个错误,说我需要凭据,这是有道理的,因为有进入接口所需的凭据。但是我不知道如何使这项工作。

我的代码如下

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var lightOn: UIButton!
@IBAction func lightOn(_ sender: Any) {

    guard let url = URL(string: "http://0.0.0.0/rest/nodes/ZW002_1/cmd/DFON") else { return }

    let userCredential = URLCredential(user: "admin",
                                       password: "admin",
                                       persistence: .permanent)

    URLCredentialStorage.shared.setDefaultCredential(userCredential, for: protectionSpace)

    // create URL session ~ defaulted to GET

    let session = URLSession.shared

    session.dataTask(with: url) { (data, response, error) in

        // optional chaining to make sure value is inside returnables and not not

        if let response = response {
            print(response)
        }

        if let data = data {

            // assuming the data coming back is Json -> transform bytes into readable json data

            do {

                let json = try JSONSerialization.jsonObject(with: data, options: [])

                print(json)

            }   catch {

                print("error")
            }
        }

        }.resume() // if this is not called this block of code isnt executed

}

}

我尝试在线拼凑几个例子,我见过的那些使用protectSpace但是当我使用它时代码返回:

Use of unresolved identifier 'protectionSpace'

总而言之,每当我实际运行模拟器时,我都会得到这个确切的错误:

2017-12-26 13:28:58.656122-0600 hohmtest[6922:1000481] CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
atyp = http;
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = http;
"r_Attributes" = 1;
sdmn = "/";
srvr = "192.168.1.73";
sync = syna;
}
<NSHTTPURLResponse: 0x60400042a3e0> 
{ URL:         
http://192.168.1.73/rest/nodes/ZW002_1/cmd/DON/ } { Status Code: 401, 
Headers {
"Cache-Control" =     (
    "max-age=3600, must-revalidate"
);
Connection =     (
    "Keep-Alive"
);
"Content-Length" =     (
    0
);
"Content-Type" =     (
    "text/html; charset=UTF-8"
);
EXT =     (
    "UCoS, UPnP/1.0, UDI/1.0"
);
"Last-Modified" =     (
    "Tue, 26 Dec 2017 11:26:15 GMT"
);
"Www-Authenticate" =     (
    "Basic realm=\"/\""
);
} }
error
ios swift rest api
1个回答
3
投票

这个解决方案对我有用。这就是我调用需要用户名和密码的REST API的方法。对于那些想知道的人,我把这个代码放在我的IBAction按钮里,除了制作按钮之外别无他法。

let username = "admin"
let password = "admin"
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()

// create the request
let url = URL(string: "http:/rest/nodes/ZW002_1/cmd/DFON")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginData)", forHTTPHeaderField: "Authorization")

//making the request
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("\(error)")
        return
    }

    if let httpStatus = response as? HTTPURLResponse {
        // check status code returned by the http server
        print("status code = \(httpStatus.statusCode)")
        // process result
    }
}
task.resume()

*********额外注意*************

如果您的用户名和密码没有,并且您尝试在swift中调用REST API调用,那么可以使用一些代码来帮助您!两者都得到了要求!

@IBAction func onGetTapped(_ sender: Any) {

    guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { return }

    // create URL session ~ defaulted to GET

    let session = URLSession.shared

    session.dataTask(with: url) { (data, response, error) in

        // optional chaining to make sure value is inside returnables and not not

        if let response = response {
            print(response)
        }

        if let data = data {

            // assuming the data coming back is Json -> transform bytes into readable json data

            do {

                let json = try JSONSerialization.jsonObject(with: data, options: [])

                print(json)

            }   catch {

                print("error")
            }
        }

        }.resume() // if this is not called this block of code isnt executed

}
© www.soinside.com 2019 - 2024. All rights reserved.