无法将'NSMutableURLRequest'(0x11beb7040)类型的值转换为'Alamofire.URLRequestConvertible'(0x11beb9040)

时间:2016-12-13 06:12:10

标签: swift3 alamofire

构建我的代码然后在Alamofire.request(request as! URLRequestConvertible).responseJSON()崩溃。请提示如何修复此崩溃

let url = NSURL(string: "https://jsonplaceholder.typicode.com/users")
let request = NSMutableURLRequest(url:url! as URL)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

Alamofire.request(request as! URLRequestConvertible).responseJSON(){ response in

       switch response.result
       {
          case .success(let data):                
             print(" i got my Data Yup",data)          
          case .failure(let error):
             print(error)                                
        }
    }

3 个答案:

答案 0 :(得分:16)

在Swift 3中,您所要做的就是将NSMutableURLRequest更改为URLRequest,它将起作用。不需要施放。 另外,设置var以便它可以快速变化。 :)谢谢,马库斯发表评论。

答案 1 :(得分:6)

let request = NSMutableURLRequest(url:url! as URL)更改为     var request = URLRequest(url: NSURL(string: url)! as URL) 你的代码看起来像这样: -

    let url = NSURL(string: "https://jsonplaceholder.typicode.com/users")
    var request = URLRequest(url: NSURL(string: url)! as URL)
    request.httpMethod = "GET"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    Alamofire.request(request as! URLRequestConvertible).responseJSON(){ response in

           switch response.result
           {
              case .success(let data):                
                 print(" i got my Data Yup",data)          
              case .failure(let error):
                 print(error)                                
            }
        }

答案 2 :(得分:0)

您还可以尝试使用以下语法来处理请求方法:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:kafka-outbound-context.xml"
        })
public class ProducerTest{

    @Autowired
    @Qualifier("inputToKafka")
    MessageChannel channel;

    @Test
    public void test_send_message() {

        channel.send(MessageBuilder.withPayload("Test Message")
                .setHeader(KafkaHeaders.TOPIC, "test").build());

    }

}