如何在 swift4 中使用 Rxalamofire 发送 URL 请求

Posted

技术标签:

【中文标题】如何在 swift4 中使用 Rxalamofire 发送 URL 请求【英文标题】:How to send URL Request using Rxalamofire in swift4 【发布时间】:2019-04-03 13:18:54 【问题描述】:

实际上我是 ios 新手,现在我的任务是使用 Rxalamofire 发送 URL 请求。我完全不知道 Rxalamofire。以前我只使用 alamofire。以前我只使用 alamofire。现在我也像以前使用以前一样发送了 url 请求,但后来我发现 Rxalamofire 比 alamofire 好得多。不幸的是我无法发送 URL 请求。所以,谁能告诉我一步一步的过程。在此先感谢。

 postParameters = ["username":mailid,"password":password]

            Alamofire.request(Constants.loginapi, method: .post, parameters: postParameters, encoding: URLEncoding.default, headers: nil).responseJSON   response in
                switch response.result 
                case .success:
                    print(response)
                  case .failure(let error):
                    print(error)
                

            

【问题讨论】:

【参考方案1】:

我看到你之前的帖子在 MVVM/RxSwift 上苦苦挣扎。

你可以在这里找到一个可以帮助你关注的项目-

    RXSwift + MVVM Rxswift + Alamofire

https://github.com/saurabh-360/RxAlamofireDemo

对于问题,您可以通过标准方式发送请求,

但是在使用 RXswift API 时,使用 Observable 模式是更好的方法,它是观察数据流。

以下代码可以帮助您入门。

func loginUser() -> Observable<Any>? 

    return Observable<Any>.create(observer in
        /**
         parameters or additional headers we can bind with the url request
         the case is standard here like we do in URLSession requests
         consider this example to incorporate the same
         https://***.com/a/40608923/4549304
         */
        let parameters:[String:String] = ["username":"Your username value here",
                                          "password":"Your password value here"]

        /**
         There are multiple ways to request data from the servers using
         Default ALamofire methods
         I am using Alamofire.request(String) method here for the same.


         We Can also use
         request(_ urlRequest: URLRequestConvertible)
         method in case we want to make a post request
         with additional headers and parameters

         */

        Alamofire.request("https://reqres.in/api/login", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil)
            .response  response in
                if response.response?.statusCode == 400 
                    print("authorisation error")

                    // you need to exit the request here since there was error and
                    // no parsing is needed further for the response
                    // you can also send and error using the observer.OnError(Error)
                    return observer.onCompleted()
                

                // convert data to our model and update the local variable
                guard let responseData =  response.data else 
                    return observer.onCompleted()
                
                do 
                    let model = try JSONDecoder().decode(YourModel.self, from: responseData)
                    observer.onNext(model)
                    observer.onCompleted()
                catch 
                    observer.onError(error)
                    observer.onCompleted()
                    print("some thing went wrong.")
                
        

        return Disposables.create();
    )

【讨论】:

我试过这个。我在 ViewModel 类中实现了这个代码。但是我收到一个错误,比如“在参数类型 'Model.Type' 中,'Model' 不符合预期的类型 'Decodable'”在这一行“让模型 = 尝试 JSONDecoder().decode(YourModel.self, from: responseData)” Yourmodel 是您希望在其中建模数据的结构...请在我共享后浏览 github 链接 示例。或者您可以评论该行并以字符串格式打印响应.. 我采用了一个数组类型(Array.self)。我在 viewmodel 类中编写了这个函数。我在控制器类中的按钮操作中调用它,如 var loginscreen:viewmodel? loginscreen!.loginUser() 即使当我单击按钮时它没有被调用。我什么也没得到。 在上述情况下,您的 loginScreen 变量将为 nil,因为它是可选的且未初始化,要使其正常工作,您需要进行初始化,这可以在 viewDidLoad 中通过 loginscreen = viewModel( )。另外你能分享你的代码吗?一个github链接就可以了,我们可以在那里讨论它。

以上是关于如何在 swift4 中使用 Rxalamofire 发送 URL 请求的主要内容,如果未能解决你的问题,请参考以下文章

如何在 swift4 中使用 Rxalamofire 发送 URL 请求

如何使用MVVM + Swift4实现注册屏幕

如何在swift4中动态添加滚动视图

如何在 swift4 中获得蓝牙外设的特征值?

如何在 Swift4 中不使用 inputIntensity 参数控制 CIFilter 的强度?

如何删除空白存档的Xcode文件(swift4)