在Swift中的AsynchronousRequest之后NSData是nil

时间:2016-03-03 21:25:00

标签: swift http request nsdata

我正在尝试将视频数据添加到HTTP请求的正文中,但有时视频数据会变为零但有时不会。有什么可以解决这种情况吗?当我从我的应用程序中删除应用程序并再次进行模拟后,没有任何反应。

  @IBAction func post(sender: AnyObject) {

    let videodata = NSData(contentsOfURL: videoURL!)
    let headers = [
        "authorization": "Token \(userToken!)",
        "content-type": "/*/",
        "content-disposition": "attachment;filename=deneme.mp4",
        "cache-control": "no-cache"
    ]
    let request = NSMutableURLRequest(URL: NSURL(string: "http://molocate.elasticbeanstalk.com/video/upload/")!,
        cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData,
        timeoutInterval: 10.0)
    request.HTTPMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.HTTPBody = videodata

    let session = NSURLSession.sharedSession()
    let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            //print(NSString(data: data!, encoding: NSUTF8StringEncoding))
            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)

                print("Result -> \(result)")
                let statue = result["result"] as! String
                if(statue == "success"){
                    let videoId = result["video_id"] as! String
                    let videoUrl = result["video_url"] as! String
                    print(videoUrl)
                    let json = [
                        "video_id": videoId,
                        "video_url": videoUrl,
                        "caption": "This city is awesome:)",
                        "category": "travel",
                        "tagged_users": [["username": "amertturker"]],
                        "location": [
                            [
                                "id": "mekmaekfmaıhjagej3ıo45j3kt348t3gkg",
                                "latitude": "35.342643",
                                "longitude": "32.345236",
                                "name": "Milas Merkez Kafasına göre herkes",
                                "address": "Milas aq"
                            ]
                        ]
                    ]

                    let newheaders = [
                        "authorization": "Token \(userToken!)",
                        "content-type": "application/json",
                        "cache-control": "no-cache"
                    ]

                    do {

                        let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
                        print(NSString(data: jsonData, encoding: NSUTF8StringEncoding))

                        // create post request
                        let url = NSURL(string: "http://molocate.elasticbeanstalk.com/video/update/")!
                        let request = NSMutableURLRequest(URL: NSURL(string: "http://molocate.elasticbeanstalk.com/video/update/")!,
                            cachePolicy: .UseProtocolCachePolicy,
                            timeoutInterval: 10.0)
                        request.HTTPMethod = "POST"
                        request.allHTTPHeaderFields = newheaders
                        request.HTTPBody = jsonData


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

                            //print(NSString(data: data!, encoding: NSUTF8StringEncoding))
                            dispatch_async(dispatch_get_main_queue(), {
                                if error != nil{
                                    print("Error -> \(error)")

                                    return
                                }

                                do {

                                    let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)


                                    print("Result -> \(result)")



                                } catch {
                                    print("Error -> \(error)")
                                }
                            })
                        }

                        task.resume()




                    } catch {
                        print(error)


                    }



                } else{
                    //                        self.displayAlert("Hata", message: result["result"] as! String)
                    //                        UIApplication.sharedApplication().endIgnoringInteractionEvents()
                    //                        self.activityIndicator.stopAnimating()
                    //                        self.activityIndicator.hidesWhenStopped = true
                }




            } catch {
                print("Error -> \(error)")

            }
        }
    })

    dataTask.resume()




    do {
        try NSFileManager.defaultManager().removeItemAtPath(videoPath!)  //.removeItemAtURL(fakeoutputFileURL!)
        dispatch_async(dispatch_get_main_queue()) {
            print("siiiiil")
        self.performSegueWithIdentifier("finishUpdate", sender: self)

        }
    } catch _ {

    }

1 个答案:

答案 0 :(得分:2)

您异步调用httprequest,然后尝试使用调用线程上的数据。直到http请求返回之后才会填充它,这将在未确定的未来时间发生。你想用videoData做的任何事都应该在完成处理程序中完成,否则你处于竞争状态,当你调用它时它可能是nil。