是否在电话呼叫期间执行为后台操作配置的URLSession上载任务

时间:2017-02-16 23:45:04

标签: swift background core-location nsurlsession phone-call

我正在编写一个为位置更新启用后台操作的应用程序。目的是允许一个人设置地理围栏,在进入或退出事件时触发Twilio SMS消息。

我玩了几个设置,目前只使用以下会话设置:

configuration = URLSessionConfiguration.background(withIdentifier: Constants.twilioBackgroundSessionIdentifier)

    configuration.isDiscretionary = false

    bgSession = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    // Build the request
    let completeURL = URL(string: "https://" + Constants.twilioSSLHostName + Constants.twilioSendSMSURL)

    // Create request and https header
    let req = NSMutableURLRequest(url: completeURL!)
    req.httpMethod = Constants.httpMethod.post
    req.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")

    // Create Twilio required Parms for Send SMS POST
    let countryCode = "+1"
    let httpBodyString = "to=" + countryCode + sendToNumber + "&message=" + message
    //NSLog("Body string: \(httpBodyString)")

    //Need a File for the background uploadTaskWithRequest                          //
    //the request contains the real information                                     //
    let fileManager = FileManager()
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let fileName = path + "/Twillio.html"
    var fileURL: URL!

    if fileManager.fileExists(atPath: fileName) {
        //Remove the tempory file
        do {
            try fileManager.removeItem(at: URL(fileURLWithPath: fileName))
        } catch {
            //NSLog("TwilioManager:sendSMS:unable to remove tmp file")
        }
    }
    let remoteSeverValueString : String = httpBodyString

    do {
        try remoteSeverValueString.write(toFile: fileName, atomically: true, encoding: String.Encoding.utf8)
    } catch {
        // failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
        //NSLog("TwilioManager:sendSMS:Unable to write file")
    }
    fileURL = URL(fileURLWithPath: fileName)

    let contentLength = fileManager.contents(atPath: fileName)!.count

    req.setValue(String(contentLength), forHTTPHeaderField: "Content-Length")

    upLoadTask = bgSession.uploadTask(with: req as URLRequest, fromFile: fileURL)
    // Set task to highest priority
    upLoadTask.priority = 1.0

    upLoadTask.resume()

    bgSession.finishTasksAndInvalidate()

我使用.isDiscretionary = false并将task.priority设置为1.0来改善后台响应能力。

当我在位置活动期间进行正常通话时,我不会收到短信,直到我挂机然后立即出现(即使应用程序在后台)。我不知道位置更新或上传任务是否被延迟。

我意识到Apple对依赖后台操作的应用程序表示不满,但这适用于残障人士,并且允许他们使用始终运行的应用程序,实时向家人和朋友发送警报。

我可以做些什么来在电话呼叫期间进行位置更新和/或上传任务?

0 个答案:

没有答案