Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

based on this answer I modified my code. Is this the correct approach now?

   func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    var userId = "001" //I just use it as USER number 1

    let token = deviceToken.hexString()

        var postBody = NSString(format: "user=%@&token=%@", userId, token)
        var endBody = NSURL(string: "http://www.myServer.com/api/v1.0/register.php")
        var request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)


        request.HTTPMethod = "POST";
        request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")


        var response: NSURLResponse?
        var error: NSError?


        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
            (response, data, error) -> Void in

            if data != nil {
                println("data: \(response)")

            } else {

                println("failed: \(error.localizedDescription)")
            }
        }
  }




   extension NSData {
func hexString() -> String {
    // "Array" of all bytes:
    let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
    // Array of hex strings, one for each byte:
    let hexBytes = map(bytes) { String(format: "%02hhx", $0) }
    // Concatenate all hex strings:
    return "".join(hexBytes)
    }
   }
share|improve this question

First of all I think you could improve indenting (use Xcode built-in tool) and spaces.

Second thing you had 2 useless local variables.

And, most important, IMO you should create a struct or a class as your API client wrapper. Even if you have one simple method for now.

Here is a very simplified example.

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    var userId = "001" //I just use it as USER number 1
    let token = deviceToken.hexString()

    let apiClient = MyRESTAPI(userId: "001")
    apiClient.setUserToken(token) {
        result in
        switch result {
        case .Ok(let response):
            println("data: \(response)")
        case .Error(let error):
            println("failed: \(error.localizedDescription)")
        }
    }
}


    struct MyRESTAPI {
        enum Result {
            case Error(NSError)
            case Ok(NSURLResponse)
        }

        let userId:String

        func setUserToken(token:String, completion:(Result -> Void)) {
            var postBody = NSString(format: "user=%@&token=%@", self.userId, token)
            var endBody = NSURL(string: "http://www.myServer.com/api/v1.0/register.php")
            var request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)

            request.HTTPMethod = "POST";
            request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
                (response, data, error) -> Void in

                if data != nil {
                    completion(MyRESTAPI.Result.Ok(response))
                } else {
                    completion(MyRESTAPI.Result.Error(error))
                }
            }
        }
    }


    extension NSData {
        func hexString() -> String {
            // "Array" of all bytes:
            let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
            // Array of hex strings, one for each byte:
            let hexBytes = map(bytes) { String(format: "%02hhx", $0) }
            // Concatenate all hex strings:
            return "".join(hexBytes)
        }
    }
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.