简体   繁体   English

在iOS中访问Magento Rest API-Swift 3.0

[英]Access Magento Rest API in iOS - swift 3.0

I want to access the magenta REST API in my iOS application. 我想在我的iOS应用程序中访问洋红色REST API。 Following is my code to access the API: 以下是我访问API的代码:

func getCustomerTokenusingURLSEssion(){

    let url = URL(string: "HTTPURL")!
    var urlRequest = URLRequest(
        url: url,
        cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
        timeoutInterval: 10.0 * 1000)
    urlRequest.httpMethod = "POST"
    urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")

    let json1: [String: Any] = [
        "username": "xyz@gmail.com",
        "password":"xyz12345"]

    let jsonData = try? JSONSerialization.data(withJSONObject: json1, options: .prettyPrinted)

    urlRequest.httpBody = jsonData
    let config = URLSessionConfiguration.default
    let urlsession = URLSession(configuration: config)

    let task = urlsession.dataTask(with: urlRequest){ (data, response, error) -> Void in

        print("response from server: \(response)")

        guard error == nil else {
            print("Error while fetching remote rooms: \(error)")
            return
        }
        guard let data = data,
            let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                print("Nil data received from fetchAllRooms service ")
                return
        }

        print("JSON \(json)")

    }
    task.resume()

}

But I'm getting error message form the server as follow: 但是我从服务器收到错误消息,如下所示:

["message": Server cannot understand Content-Type HTTP header media type application/x-www-form-urlencoded] [“消息”:服务器无法理解Content-Type HTTP标头媒体类型application / x-www-form-urlencoded]

Please help! 请帮忙! Thanks! 谢谢!

Here's working example of token-based authentication from iOS to magento2 using swift: 这是使用Swift从iOS到magento2的基于令牌的身份验证的工作示例:

func restApiAuthorize(completionBlock: @escaping (String) -> Void) {
        // Prepare json data
        let json: [String: Any] = ["username": “yourusername”,
                                   "password": “yourpassowrd”]

        let jsonData  = try? JSONSerialization.data(withJSONObject: json)

        // Create post request
        let url = URL(string: "http://yourmagentodomain.com/index.php/rest/V1/integration/customer/token")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("\(jsonData!.count)", forHTTPHeaderField: "Content-Length")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        // Insert json data to the request
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }
            // 1: Check HTTP Response for successful GET request
            guard let httpResponse = response as? HTTPURLResponse
                else {
                    print("error: not a valid http response")
                    return
            }

            print(httpResponse.statusCode)

            switch (httpResponse.statusCode)
            {
            case 200:

                let responseData = String(data: data, encoding: String.Encoding.utf8)!
                print ("responseData: \(responseData)")

                completionBlock(responseData)

            default:
                print("POST request got response \(httpResponse.statusCode)")

            }            
        }        
        task.resume()
    }

And usage is like that: 用法是这样的:

restApiAuthorize() { (output) in
    // token data, I found it important to remove quotes otherwise token contains extra quotes in the end and beginning of string
    let userToken = output.replacingOccurrences(of: "\"", with: "")
    print ("userToken \(userToken)")
}

you can then write your userToken to userDefaults and make feature api calls. 然后可以将userToken写入userDefaults并进行功能api调用。

您忘记设置内容类型的最佳访客,因此添加以下内容:

urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM