2017-12-26 15 views
0

스위치를 켜기 위해 범용 장치 허브에 REST API 호출을하려고합니다. 통화가 진행되는 것처럼 보이지만 인터페이스에 들어가기 위해 필요한 자격 증명이 있기 때문에 자격 증명이 필요하다는 오류가 표시됩니다. 그러나 나는이 일을하는 방법을 모르겠습니다.일치하는 신용을 복사하는 중 오류가 발생했습니다 - Swift (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 

} 

} 

이며, 사람은 내가 사용 protectionSpace을 보았다하지만 난 그것을 코드를 반환 사용할 때 : 또한

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 
+0

API에 대한 설명서가 없지만 엔드 포인트에서 URLCredential을 사용하지 않을 것으로 예상됩니다. 일반적으로 헤더 나 본문을 통해 userId/PW를 전송하는 API가 표시되며 토큰을 다시 보냅니다. 그런 다음 후속 API 호출을 위해 본문을 통해 토큰을 BACK에 보냅니다. – ghostatron

답변

0

T 그의 해결책은 나를 위해 일했습니다. 이것이 사용자 이름과 비밀번호가 필요한 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() 

********* EXTRA 참고 *************

당신은 사용자 이름과 암호를 가지고 있지 않으며, 당신은 전화를 시도하는 경우 신속한 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 

} 
+0

나는 당신을 감사하는 것을 거의 잊었다 !! 이것은 놀라운 도움이었다 !! 무리 감사!! – Matherz