简体   繁体   English

Swift:尝试与Web API通信时出错

[英]Swift: error when trying to communicate with web API

I am trying to build a really basic iOS app using Swift - this is my first time doing so. 我正在尝试使用Swift构建一个非常基本的iOS应用程序 - 这是我第一次这样做。 Whilst the majority of it has been really straight forward. 虽然其中大部分都非常直接。 I have had a total nightmare getting the app to talk to my API, or any site in general! 我有一个完整的噩梦让应用程序与我的API或任何网站交谈!

This is the code i'm using, and specifically the code which is erroring: 这是我正在使用的代码,特别是错误的代码:

     NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{     (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
         println(NSString(data: data, encoding: NSUTF8StringEncoding))
     })

it's the 'NSString(data: data, encoding: NSUTF8StringEncoding)' that errors 这是'NSString(数据:数据,编码:NSUTF8StringEncoding)'的错误

I've gone through as many tutorials as I can find, and they all return me the same problem. 我已经经历了尽可能多的教程,他们都回答了我同样的问题。 I get an error saying: 我收到一个错误说:

NSURLErrorDomain - code: 4294966291 NSURLErrorDomain - 代码:4294966291

I also get a 'EXC_BAD_INSTRUCTION' error with: EXC_1386_INVOP, sub code = 0x0 (which hasn't led me to a solution... 我还得到一个'EXC_BAD_INSTRUCTION'错误:EXC_1386_INVOP,子代码= 0x0(这还没有让我找到解决方案......

Which makes me think that I haven't done something right in my set up, or something should be turned on in my preferences, or something along those lines as opposed to my code... 这让我觉得我没有在我的设置中做正确的事情,或者应该在我的偏好中开启某些东西,或者与我的代码相对的东西......

this is my whole code: 这是我的全部代码:

    var URL: NSURL = NSURL(string: "http://stackoverflow.com")

    var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"

    var bodyData = "key1=value&key2=value&key3=value"

    println(URL)
    println(bodyData)

    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    })

Update: 更新:

Using Rob's code, I know get an error printed: 使用Rob的代码,我知道打印出错误:

sendAsynchronousRequest error: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." sendAsynchronousRequest错误:错误域= NSURLErrorDomain代码= -1005“网络连接丢失。” UserInfo=0x7beafcc0 {NSErrorFailingURLStringKey= http://stackoverflow.com , _kCFStreamErrorCodeKey=57, NSErrorFailingURLKey= http://stackoverflow.com , NSLocalizedDescription=The network connection was lost., _kCFStreamErrorDomainKey=1, NSUnderlyingError=0x7d154ca0 "The network connection was lost."} UserInfo = 0x7beafcc0 {NSErrorFailingURLStringKey = http ://stackoverflow.com,_kCFStreamErrorCodeKey = 57,NSErrorFailingURLKey = http: //stackoverflow.com,NSLocalizedDescription =网络连接丢失。,_ kCFStreamErrorDomainKey = 1,NSUnderlyingError = 0x7d154ca0“网络连接丢失。“}

It sounds like data is nil . 听起来datanil Examine the contents of the error object, and it should give you an indication of why. 检查error对象的内容,它应该告诉您原因。 Most likely, there's something wrong with the request , but unless we can reproduce the problem, it's hard to diagnose. 最有可能的是, request ,但除非我们能够重现问题,否则很难诊断出来。

Anyway, if you want to perform the request with a little more diagnostic information (log error if there is a problem, log statusCode and response if status code was not 200, etc.): 无论如何,如果你想用更多的诊断信息执行请求(如果有问题则记录日志error ,如果状态代码不是200则记录statusCoderesponse等):

NSURLConnection.sendAsynchronousRequest(request, queue: queue) {
    response, data, error in

    if data == nil {
        println("sendAsynchronousRequest error: \(error)")
        return
    }

    if let httpResponse = response as? NSHTTPURLResponse {
        let statusCode = httpResponse.statusCode
        if statusCode != 200 {
            println("sendAsynchronousRequest status code = \(statusCode); response = \(response)")
        }
    }

    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

In your revised question, you shared the resulting NSError , which reported -1005 (which, in retrospect, is the same as the 4294966291 error code you showed us earlier; the latter being the the unsigned integer representation of -1005 ). 在您修改过的问题中,您共享了生成的NSError ,它报告了-1005 (回想起来,它与您之前显示的4294966291错误代码相同;后者是-1005的无符号整数表示)。 This error (as the description describes) is for NSURLErrorNetworkConnectionLost (which is kCFURLErrorNetworkConnectionLost ), for which the documentation says, "Returned when a client or server connection is severed in the middle of an in-progress load." 此错误(如说明所述)适用于NSURLErrorNetworkConnectionLostkCFURLErrorNetworkConnectionLost ),文档中说“在正在进行的加载过程中切断客户端或服务器连接时返回”。

Unfortunately, this error is used for a diverse array of issues, and as I'm unable to reproduce the error you describe, it's hard to diagnose. 不幸的是,这个错误用于各种各样的问题,因为我无法重现你描述的错误,所以很难诊断。


One thing that is missing from the request is the specification of the Content-Type : 请求中缺少的一件事是Content-Type的规范:

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

That wouldn't cause the problem you describe, but it's good practice to always inform the server of the type of the request. 这不会导致您描述的问题,但最好始终通知服务器请求的类型。

I solved this, partly thanks to Rob's answers and general help - that was very useful. 我解决了这个问题,部分归功于Rob的答案和一般帮助 - 这非常有用。

The Key in the end though, was super simple and taken from this question: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." 最后的密钥非常简单,并且从这个问题中得出Error Domain = NSURLErrorDomain Code = -1005“网络连接丢失了。”

I just had to restart the simulator. 我只需重新启动模拟器。 However I wouldn't have gotten there without the additional if data == nil {} statement. 但是如果没有额外的if data == nil {}语句,我就不会有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM