【问题标题】:NSURLSession error with PHP connectionPHP连接的NSURLSession错误
【发布时间】:2015-10-01 08:14:42
【问题描述】:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    if error != nil {
        println("error=\(error)")
        return
    }

在这段代码中,我的 PHP 连接出现 dataTaskWithRequest(request) 错误。在迁移到 Swift 2 之前它可以工作。

【问题讨论】:

    标签: swift2 nsurlsession


    【解决方案1】:

    这是正确的语法:

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    
        // your code
    
    })
    

    来自this答案的示例代码:

    var url : NSURL = NSURL(string: "https://itunes.apple.com/search?term=\(searchTerm)&media=software")
    var request: NSURLRequest = NSURLRequest(URL: url)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: config)
    
    let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    
        // notice that I can omit the types of data, response and error
    
        // your code
    
    });
    
    // do whatever you need with the task
    

    更新:

    let url : NSURL = NSURL(string: "https://itunes.apple.com/search?term=&media=software")!
        let request: NSURLRequest = NSURLRequest(URL: url)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)
    
        let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    
            do {
                let JSON = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions(rawValue: 0))
                guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
                    print("Not a Dictionary")
                    //get your JSONData here from dictionary.
    
                    return
                }
                print("JSONDictionary! \(JSONDictionary)")
            }
            catch let JSONError as NSError {
                print("\(JSONError)")
            }
    
        })
    

    【讨论】:

    • 也许你知道如何解决这个问题?因为我不明白
    • 如果我输入这个“if let json = NSJSONSerialization.JSONObjectWithData(dataObject?, options: NSJSONReadingOptions.MutableContainers) {”
    • 它在新的 xcode 像那样工作之前给了我“使用未解析的识别器数据对象”
    • 很高兴为您提供帮助..:)
    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2018-11-21
    • 2014-07-07
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多