首页 > 解决方案 > swift中对api的Http后台请求

问题描述

我有许多使用 http 请求的 api。我需要它们在后台工作,以防用户将应用程序放在后台并且有一个 api 没有完成 rquest 过程。我使用了这个函数,但它不起作用,它说:没有完全匹配调用类方法'jsonObject'

    var request = URLRequest(url: URL(string:""!)
    
    request.httpMethod = "POST"
    
    request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    
    let configuration = URLSessionConfiguration.background(withIdentifier: "app")
    configuration.allowsCellularAccess = true
    
    let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
   

    let task = session.downloadTask(with: request) { data, response, error in

        if error != nil {
            // Handle error…
            handler("Connection Error")
            return
        }
        let parsedResult: [String: AnyObject]!
        do {

            parsedResult = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
            print(parsedResult)


        } catch {
            handler("Error loading data")
            return
        }

        if parsedResult["response_code"] as? Int == 24{
            handler("success")
        }else if parsedResult["response_code"] as? Int == 255{
            handler("unauthorized")
        }
        else{
            handler("\(parsedResult["response_code"] as? Int ?? 0)")
        }

        handler(nil)
    }
    
    task.resume()

标签: iosswiftxcodehttpbackground-repeat

解决方案


推荐阅读