访问iOS中的Magento Rest API - swift 3.0

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

我想在我的iOS应用程序中访问洋红色REST 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": "[email protected]",
        "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()

}

但我从服务器收到错误消息如下:

[“message”:服务器无法理解Content-Type HTTP标头媒体类型application / x-www-form-urlencoded]

请帮忙!谢谢!

ios swift web-services magento xcode8
2个回答
0
投票

最好的访客你忘了设置你的内容类型,所以添加这个:

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


0
投票

这是使用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()
    }

用法是这样的:

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)")
}

然后,您可以将userToken写入userDefaults并进行功能api调用。

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