2015-09-17 111 views
1

我一直在試圖找出什麼是錯的白衣我的代碼,但我不斷收到這個錯誤在SWIFT 2.0雨燕2.0 URL POST請求

Errors thrown from here are not handled because the enclosing catch is not exhaustive 

的自動轉換,從XCode中做了很多工作,爲我(也給了很多錯誤),但這仍然不起作用。我不明白什麼是工作,所以也許你們可以對案件提出一些看法。在此先感謝

這裏是我的代碼

if config.isConnected() { 
     let post:NSString = "postID=\(postID)" 
     //NSLog("PostData: %@",post); 
     let url:NSURL = NSURL(string:"https://www.example.com/json/index.php")! 
     let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! 
     let postLength:NSString = String(postData.length) 

     let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) 
     request.HTTPMethod = "POST" 
     request.HTTPBody = postData 
     request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") 
     request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
     request.setValue("application/json", forHTTPHeaderField: "Accept") 

     var reponseError: NSError? 
     var response: NSURLResponse? 

     var urlData: NSData? 
     do { 
      urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) // gives error 
     } catch let error as NSError { 
      print(reponseError) 
      reponseError = error 
      urlData = nil 
     } 
     if (urlData != nil) { 
      Webiew.loadRequest(request) 
     } else { 
      let alert: UIAlertView = UIAlertView(title: "OOPS", message: "There is nothing here!", delegate: nil, cancelButtonTitle: "OK"); 
      alert.show() 
     } 
    } else { 
     // not connected 
    } 

回答

4

試試這個代碼*解釋裏面*

let parameters = ["userId":"1", "userName":"2"] as Dictionary<String, String> 
    //create the url with NSURL 
    let url = NSURL(string: "URL") //change the url 

    //create the session object 
    let session = NSURLSession.sharedSession() 
    let request = NSMutableURLRequest(URL: url!) 
    request.HTTPMethod = "POST" //set http method as POST 

    //request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body 

    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
    request.setValue("application/json", forHTTPHeaderField: "Accept") 
    request.setBodyContent(parameters) 
    //create dataTask using the session object to send data to the server 
    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
     // println("Response: \(response)") 
     let strData = NSString(data: data!, encoding: NSUTF8StringEncoding) 
     print("Body: \(strData)") 
     let json = try!NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! NSDictionary 
     print("account data") 
     completion(result: json as NSDictionary?) 


     // Did the JSONObjectWithData constructor return an error? If so, log the error to the console 
     if(error != nil) { 
      print(error!.localizedDescription) 
      let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding) 
      print("Error could not parse JSON: '\(jsonStr)'") 
     } 
     else { 
      // The JSONObjectWithData constructor didn't return an error. But, we should still 
      // check and make sure that json has a value using optional binding. 
      if let parseJSON = json as NSDictionary! { 
       // Okay, the parsedJSON is here, let's get the value for 'success' out of it 
       _ = parseJSON["success"] as? Int 
       //println("Succes: \(success)") 
      } 
      else { 
       // Woa, okay the json object was nil, something went worng. Maybe the server isn't running? 
       _ = NSString(data: data!, encoding: NSUTF8StringEncoding) 
       // println("Error could not parse JSON: \(jsonStr)") 
      } 
     } 

    }) 

    task.resume() 

添加此擴展名:

extension NSMutableURLRequest { 
    func setBodyContent(contentMap: Dictionary<String, String>) { 
     var firstOneAdded = false 
     var contentBodyAsString = String() 
     let contentKeys:Array<String> = Array(contentMap.keys) 
     for contentKey in contentKeys { 
      if(!firstOneAdded) { 

       contentBodyAsString = contentBodyAsString + contentKey + "=" + contentMap[contentKey]! 
       firstOneAdded = true 
      } 
      else { 
       contentBodyAsString = contentBodyAsString + "&" + contentKey + "=" + contentMap[contentKey]! 
      } 
     } 
     contentBodyAsString = contentBodyAsString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! 
     self.HTTPBody = contentBodyAsString.dataUsingEncoding(NSUTF8StringEncoding) 
    } 
} 
+0

幾乎沒有,只有一個警告,我無法擺脫掉, contentBodyAsString = contentBodyAsString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! 不推薦使用'stringByAddingPercentEscapesUsingEncoding':改爲使用stringByAddingPercentEncodingWithAllowedCharacters(_ :),它始終使用推薦的UTF-8編碼,並對特定的URL組件或子組件進行編碼,因爲每個URL組件或子組件對於哪些字符有效。 從xcode提出的解決方案不起作用 –

+0

同樣在這裏,對我來說它的工作,但有相同的警告。所以我沒有太注意這一點。任何機會你可以打開關於這個新的線程? –

+0

它的粉碎或它劑量甚至得到迴應? –

0

這是我的解決方案,我做不需要使用你所做的擴展。 這種方式的請求是同步的,它直接給我的迴應,我解析它來獲取值。它採取了一些搜索和試驗&錯誤,但它是解決:)我粘貼下面的代碼是別的東西,但原理是一樣的

let request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: config.versionURL() as String)!) 
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
    request.setValue("application/json", forHTTPHeaderField: "Accept") 
    var response: NSURLResponse? 

    if config.isConnected() { 
     var urlData: NSData? 
     do { 
      urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response) 
     } catch _ { 
      urlData = nil 
     } 
     if (urlData != nil) { 
      let myJSON = try! NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableLeaves) as? NSDictionary 
      if let parseJSON = myJSON { 
       onlineVersion = parseJSON["version"]?.integerValue 
       if onlineVersion > prefs.integerForKey("offlineVersion") { 
        showActivityIndicator(self.view) 
        self.structureSetup() 
       } else if onlineVersion == prefs.integerForKey("offlineVersion") { 
        if (fileExistance) { 
         let jsonStringData = NSDictionary(contentsOfFile: jsonFilePath) 
         fullStructure = JSON(jsonStringData!) 
         numCats = fullStructure["posts"].count 
         self.homeTable.reloadData() 
         hideActivityIndicator(self.view) 
        } else { 
         if config.isConnected() { 
           self.structureSetup() 
         } else { 
          // alert, nothing here 
         } 
        } 
       } 
      } 
     } 
    } else { 
     if (fileExistance) { 
      let jsonStringData = NSDictionary(contentsOfFile: jsonFilePath) 
      fullStructure = JSON(jsonStringData!) 
      numCats = fullStructure["posts"].count 
      self.homeTable.reloadData() 
     } else { 
      if config.isConnected() { 
       self.structureSetup() 
      } else { 
       // alert, nothing here 
      } 
     } 
    }