Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在iOS-swift 3.0中访问Magento Rest API_Ios_Swift_Web Services_Magento_Xcode8 - Fatal编程技术网

在iOS-swift 3.0中访问Magento Rest API

在iOS-swift 3.0中访问Magento Rest API,ios,swift,web-services,magento,xcode8,Ios,Swift,Web Services,Magento,Xcode8,我想访问iOS应用程序中的洋红RESTAPI。 以下是我访问API的代码: func getCustomerTokenusingURLSEssion(){ let url = URL(string: "HTTPURL")! var urlRequest = URLRequest( url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterv

我想访问iOS应用程序中的洋红RESTAPI。 以下是我访问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()

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

[“消息”:服务器无法理解内容类型HTTP头媒体类型应用程序/x-www-form-urlencoded]

请帮忙!
谢谢

Best Guest您忘了设置内容类型,请添加以下内容:


urlRequest.addValue(“application/json”,forHTTPHeaderField:“Content Type”)

您忘记设置内容类型了,请添加以下内容:


urlRequest.addValue(“application/json”,用于httpheaderfield:“Content Type”)

以下是使用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调用。

以下是使用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调用