【发布时间】:2015-08-25 04:18:46
【问题描述】:
我在我的服务器中调用一个函数并且应用程序崩溃了,但它在模拟器上运行良好。 我的代码:
class func changeTweet(tweet:String)
{
let data = NSMutableData()
let urlPath: String = "http://127.0.0.1:5000/registerword?word=\(tweet)"
let url: NSURL = NSURL(string: urlPath)!
var request = NSMutableURLRequest(URL: url)
let request1: NSURLRequest = NSURLRequest(URL: url)
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?
>=nil
//crashes on this line:
let dataVal: NSData = try! NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)
var err: NSErrorPointer
let string = NSString(data: dataVal, encoding: NSUTF8StringEncoding)
if let str = string
{
print("Server Response: \(str)")
}
}
【问题讨论】:
-
为什么不将强制的
try!替换为适当的try-catch 并在失败的情况下打印错误消息?这可能会提供有关您的问题的有用信息。 -
@MartinR 你能在这里发布一个例子吗?
-
@MartinR 问题是......它适用于模拟器!
-
在“Using Swift with Cocoa and Objective-C”文档的“Catching and Handling an Error”中有记载。以下是一些示例:stackoverflow.com/a/29384651/1187415.
-
你改了网址吗? 127.0.0.1 是当前设备的ip。如果您在 Mac 上运行服务器,这可能就是原因。
标签: swift nsurlconnection ios9 xcode7