如何使用Swift 2.0

时间:2015-12-17 11:01:10

标签: ios json swift rest parse-platform

我正在尝试使用REST API将图像或文件与Parse.com中的对象相关联。 Parse.com REST API Doc非常模糊,它首先讨论如何上传哪个很好,然后如何关联。唯一的问题是,它没有显示如何与User table关联,只显示Object table,所以当我尝试与用户关联时,它会询问用户名和密码,以及响应就好像它试图创建一个新的user。当我尝试与常规表Company关联时,它会创建一个新条目。欢迎任何帮助,这是我到目前为止的代码。

这是使用REST将文件上传到Parse.com的代码

    let baseURL = NSURL(string: self.baseURL)
    let url = NSURL(string: "/1/files/pic.jpg", relativeToURL: baseURL)

    let request = NSMutableURLRequest()
    request.HTTPMethod = "\(HTTPMethod.POST)"
    request.addValue(appID, forHTTPHeaderField:  "X-Parse-Application-Id")
    request.addValue(apiKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
    request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type")

    let image = UIImage(named: "empAvatar")

    let imageData = UIImageJPEGRepresentation(image!, 0.9)
    let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

    let param = ["userProfile":base64String]

    do{
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param, options: .PrettyPrinted)
    } catch {
        print("ERROR: HTTP Body JSON")
    }

    request.URL = url
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request) {
        data, response, error in
        do {
            let imageDic = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
            print("DATA: \(imageDic)")
        } catch {

        }
    }
    task.resume()

这是将文件与用户/对象相关联的代码

let baseURL = NSURL(string: self.baseURL)
    let url = NSURL(string: "/1/users/", relativeToURL: baseURL)

    let request = NSMutableURLRequest()
    request.HTTPMethod = "\(HTTPMethod.POST)"
    request.addValue(appID, forHTTPHeaderField:  "X-Parse-Application-Id")
    request.addValue(apiKey, forHTTPHeaderField: "X-Parse-REST-API-Key")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")


   let param = ["name":"John", "picture":["name":"tfss-127e50c4-be6e-4228-b1a3-3f253358ac-pic.jpg","__type":"File"]]


    do{
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param, options: .PrettyPrinted)
    } catch {
        print("ERROR: HTTP Body JSON")
    }

    request.URL = url
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request) {
        data, response, error in
        do {
            let imageDic = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
            print("DATA: \(imageDic)")
        } catch {

        }
    }
    task.resume()

通过网址,我也试过了:

 let url = NSURL(string: "/1/class/Company/", relativeToURL: baseURL)

它刚刚创建了一个新条目。

谢谢!

1 个答案:

答案 0 :(得分:1)

POST请求将使用PUT方法创建新条目尝试。