2016-06-06 14 views
1

Ich versuche, Zugriffstoken für Instagram zu erhalten, aber häufiger Fehler You must provide client id. Ich denke, es ist ein Serialisierungsproblem, da meine Parameter nicht richtig serialisiert werden. Ich versuchte es auf POSTMAN und es funktioniert gut, aber auf NSURLSession es Fehler wirft.NSURLSession Serialisierungsfehler mit Post-Anfrage

ERROR

{ 
    code = 400; 
    "error_message" = "You must provide a client_id"; 
    "error_type" = OAuthException; 
} 

Was mache ich hier falsch, während es die Serialisierung.

let instaInfoDict = NSDictionary(objects: ["client_id","client_secret","grant_type","redirect_uri","code"], forKeys: [kCLientIdInstagram,kCLientSecretIdInstagram,"authorization_code",kRedirectUriInstagram,code]) 
// Hit post request with params 
WebServices().postRequest(kAccessTokenGenerationInstagram, bodyData: instaInfoDict, completionBlock: { (responseData) in 
       print(responseData) 

}) 


//WEBSERVICE CLASS: 

func postRequest(url:String, bodyData:NSDictionary, completionBlock:WSCompletionBlock){ 
     if let url = NSURL(string: url){ 
      let headers = [ 
       "Accept": "application/json", 
       "content-type": "application/json"] 

      let session = NSURLSession.sharedSession() 

      let request = NSMutableURLRequest(URL: url, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10) 
      request.HTTPMethod = "POST" 
      request.allHTTPHeaderFields = headers 

      request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(bodyData, options: [.PrettyPrinted]) 

      let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) in 
     if error != nil { 
      // Handle error 


      completionBlock!(responseData:nil) 
     } 
     else{ 
//Parsing the data 
      let parsedData = parseJson(response as? NSData) 

      completionBlock!(responseData: parsedData) 

     } 

      }) 

      task.resume() 
     } 


    } 

ich dies versucht haben, auch

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(bodyData, options: NSJSONWritingOptions(rawValue: 0)) 

Antwort

2

Es scheint, dass das Problem ist, dass der Content-Type application/x-www-form-urlencoded statt application/json sein sollte, auch die Möglichkeit, die Parameter mit dieser Art senden von Content-Type ändert sich ein wenig.

machte ich einen kleinen Test und dieser Code funktioniert für mich:

extension Dictionary { 

func paramsString() -> String { 
    var paramsString = [String]() 
    for (key, value) in self { 
     guard let stringValue = value as? String, let stringKey = key as? String else { 
      return "" 
     } 
     paramsString += [stringKey + "=" + "\(stringValue)"] 

    } 
    return (paramsString.isEmpty ? "" : paramsString.joinWithSeparator("&")) 
} 

}

es Hoffnung:

static func generateAccessToken() { 

    let params = ["client_id": "your_id", 
        "client_secret": "your_client_secret", 
        "grant_type": "authorization_code", 
        "redirect_uri": "http://tolkianaa.blogspot.com/", 
        "code": "the_code"] 


    guard let url = NSURL(string: "https://api.instagram.com/oauth/access_token") else { 
     return 
    } 
    let request = NSMutableURLRequest(URL: url) 
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
    request.HTTPMethod = "POST" 

    let stringParams = params.paramsString() 
    let dataParams = stringParams.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) 
    let paramsLength = String(format: "%d", dataParams!.length) 
    request.setValue(paramsLength, forHTTPHeaderField: "Content-Length") 
    request.HTTPBody = dataParams 

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in 
     var json: AnyObject = [:] 

     guard let data = data else { 
      return 
     } 

     do { 
      json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) 
     } catch { 
      // Do nothing 
     } 

     print(json) 
    } 

    task.resume() 
} 

die params in Form von String ich diese Erweiterung gemacht zu bekommen hilft!

+0

Ja, mein Fehler war, dass ich 'json' Daten gepostet habe, aber 'Instagram' akzeptiert entweder' url-kodierte oder multipart/form Daten '. – ankit