0

How do I post the request on iOS? Actually when I logged into Facebook it fetches the user informations like username, from where there are login (latitude, longitude). Is it possible to use api Link: http://buddysin.aumkiiyo.com/fbc

My code is:

@IBAction func btnAPI(sender: UIButton)
{
    //startConnection()
    connectToWebAPI()
}
func connectToWebAPI()
{ 
    //setting up the base64-encoded credentials
    let id = "1620912344817986"
    //let password = "pass"
    let loginString = NSString(format: "%@:%@", id)
    let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
    let base64LoginString = loginData.base64EncodedStringWithOptions(nil)

    //creating the requestz
    let url = NSURL(string: "http://buddysin.aumkiiyo.com/fbc")
    var request = NSMutableURLRequest(URL: url!)
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession.sharedSession()
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let urlConnection = NSURLConnection(request: request, delegate: self)
    request.HTTPMethod = "POST"
    request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")

    let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        if (error != nil) {
            println(error)
        }
        else {
            // converting the data into Dictionary
            var error: NSError?
            let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary

            println(jsonResult)
        }
    })

    //fire off the request  

    task.resume()
}

while I run, the fatal error where displayed as

`fatal error: unexpectedly found nil while unwrapping an Optional value`

in the "jsonResult"

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mahalakshmi.J
  • 189
  • 2
  • 14

4 Answers4

0

i think it is better to use Alomafire. As AFNetWorking in Objective-C it is a library which simplified a lot http request.

Pred05
  • 492
  • 1
  • 3
  • 13
  • what i should do after i download the alomafire – Mahalakshmi.J Aug 20 '15 at 13:10
  • When you have added Alomafire in your XCode Project. You can find some example in the github. For example an example to make a http.post : [link](https://github.com/Alamofire/Alamofire#post-request-with-url-encoded-parameters) – Pred05 Aug 20 '15 at 13:44
0

You should find which varible due to this error: for example data,

if let dataTemp = data as? NSDictionary {
}

FYI: Here is a way of 'POST' method of AFNetworking in swift, below code should be in your connectToWebAPI method, wrap your url ready into NSURL.

let manager = AFHTTPRequestOperationManager(baseURL: NSURL(string: yourURL))
manager.POST("path", parameters: ["key":value], success: { (opeartion:AFHTTPRequestOperation!, data:AnyObject!) -> Void in
        },failure: { (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in

    })

Tutorial to install AFNetworking. https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking

William Hu
  • 15,423
  • 11
  • 100
  • 121
  • so i should have to change the code completely write!! and where do i have to paste this code.. i have no idea about this code. – Mahalakshmi.J Aug 20 '15 at 13:16
  • if i implement this code in my connectToWebAPI() its shows some error like /* Use of Unresolved AFHTTPRequestOperationManager */ , /* Use of declared type AFHTTPRequestOperation */ . how should i resolve the errors. – Mahalakshmi.J Aug 21 '15 at 05:53
  • Oh, suggest to use *AFNetworking* for http/https on IOS development. Nearly no app with interact with backend/API won't use it. – William Hu Aug 22 '15 at 00:48
0
  • Visit this question to check for my post-request function (if
    you don't want to use Alamofire for any reasons)

  • Visit this question to check for steps you need to do if you want to add Alamofire to your XCode-project

  • If you need to get json-data from your server, use
    SwiftyJSON. It's as simple as dragging SwiftyJSON.swift into your project with checking "Copy items if needed" and using like

let jsonData = JSON(data: yourDataFromServer)

  • Also you can view this question to check out for steps to encode json-post data to send it to server.

Hope I helped :)

Community
  • 1
  • 1
SwiftStudier
  • 2,272
  • 5
  • 21
  • 43
0

It is quite easy to do with Alamofire

  func postSomething(completionHandler: @escaping CompletionHandler){
    let loginString = NSString(format: "%@:%@", id)
    let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
    let base64LoginString = loginData.base64EncodedStringWithOptions(nil)

    let headers: HTTPHeaders = [
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "base64LoginString",
    ]

    let parameters: Parameters = [
        "parameter": value,
        "parameter2": value2
    ]

    Alamofire.request("http://buddysin.aumkiiyo.com/fbc", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: SFAppServicesManager.sharedInstance.genericHeader()).responseJSON { response in
        if let JSON = response.result.value {
            let userDictionary = JSON as! NSDictionary
            completionHandler(true)
        } else {
            completionHandler(false)
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
peig
  • 418
  • 3
  • 11