ios - 在 iOS 中访问 Magento Rest API - swift 3.0

标签 ios swift web-services magento xcode8

我想在我的 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": "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()

}

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

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

求助! 谢谢!

最佳答案

这是使用 swift 从 iOS 到 magento2 的基于 token 的身份验证的工作示例:

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 调用。

关于ios - 在 iOS 中访问 Magento Rest API - swift 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43376205/

相关文章:

ios - 阻止从 UIWebView 打开 appstorelink

ios - 单个选项卡栏项目根据条件呈现不同的 View Controller ?

iphone - 核心数据图像 "unrecognised selector..."

rest - 如何将 PowerShell 调用 webrequest 与 Windows 身份验证和用户名\密码一起使用

jquery - 调用共享WebMethod时出现未知Web方法异常

ios - 通过 WIFI 将 iOS 设备与非 iOS 设备通信

ios - 如何在 Swift iOS 中通过 QR 扫描仪扫描时在日历中添加事件

swift - 如何使用 CoreBluetooth 只扫描信标

Swift 3 - 如何从另一个 View 插入 TableView 单元格?

ruby - 无法从同一网络上的另一台计算机访问本地 Sinatra 服务器