即使没有互联网连接,如何将数据和图像发布到服务器中

时间:2016-04-13 05:16:28

标签: ios swift swift2

您好我正在使用http POST数据和图片,当wifi /互联网连接可用时,它可以正常工作。但是当关闭移动数据/ wifi时,它显示了一些问题如下:

error=Optional(Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSErrorFailingURLStringKey=http://moneymonkey.tokiiyo.com/api/policy, _kCFStreamErrorCodeKey=8, NSErrorFailingURLKey=http://moneymonkey.tokiiyo.com/api/policy, NSLocalizedDescription=The Internet connection appears to be offline., _kCFStreamErrorDomainKey=12, NSUnderlyingError=0x16ef25f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8}}})

我使用HTTP post方法的代码如下:

func barButtonItemClicked(barButtonItem: UIBarButtonItem)
{


    let myUrl = NSURL(string: "http://moneymonkey.tokiiyo.com/api/policy");

    let typeItem: InsuranceType = InsuranceManager.sharedInstance.TypeArray[0]
    //let typeItem = InsuranceManager.sharedInstance
    let compItem = InsuranceManager.sharedInstance

    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";

    let param = [
        "api_key"  : "AiK58j67",
        "api_secret"    : "a#9rJkmbOea90-",
        "phone"    : "\(mobile)",
        "policy_type"   :   "\(typeItem.name)",
        "company"   :   "\(compItem.selectedCompany.cname)"
    ]

    print("Policy_type: \(typeItem.name)")
    print("Company: \(compItem.selectedCompany.cname)")
    let boundary = generateBoundaryString()

    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")



    let imageData = uploadImage?.highestQualityJPEGNSData

    if(imageData==nil)  { return; }

    request.HTTPBody = createBodyWithParameters(param, filePathKey: "file[]", imageDataKey: imageData!, boundary: boundary)


    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }

        // You can print out response object
        print("******* response = \(response)")

        // Print out reponse body
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("****** response data = \(responseString!)")
        do{

            _ = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
            dispatch_async(dispatch_get_main_queue(),{
            });
        }
        catch
        {

            // report error
          print("Oops!! Something went wrong\(error)")
        }
    }

    task.resume()

    let alert = UIAlertController(title: "Message", message:"Your document was uploaded successfully to our Server.", preferredStyle: .Alert)
    let action = UIAlertAction(title: "DONE", style: .Default) { _ in
        // Put here any code that you would like to execute when
        // the user taps that OK button (may be empty in your case if that's just
        // an informative alert)
        self.performSegueWithIdentifier("listSegue", sender: self)
    }
    alert.addAction(action)
    self.presentViewController(alert, animated: true){}

}

func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
    let body = NSMutableData();

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString1("--\(boundary)\r\n")
            body.appendString1("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString1("\(value)\r\n")
        }
    }

    let filename = "upload.png"

    let mimetype = "image/jpeg"

    body.appendString1("--\(boundary)\r\n")
    body.appendString1("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString1("Content-Type: \(mimetype)\r\n\r\n")
    body.appendData(imageDataKey)
    body.appendString1("\r\n")



    body.appendString1("--\(boundary)--\r\n")

    return body
}

func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"
}

extension NSMutableData {

func appendString1(string: String) {
    let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    appendData(data!)
}
}

任何人都可以指导我,即使没有网络连接也可以上传。提前致谢

2 个答案:

答案 0 :(得分:5)

如果互联网连接不可用,则无法上传数据。

但是,如果互联网不可用,您可以将该数据存储到本地数据库中,并且只要出现互联网连接,您就可以发布该数据。并在上传数据时从本地数据库中删除。

答案 1 :(得分:1)

无法将上传数据到服务器互联网连接在设备上无法使用。但您可以将数据保存在本地,同时检查可达性始终或某个时间间隔,当它将数据从本地数据库发送到服务器并从本地删除项目时(如果您需要)