1
\$\begingroup\$

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)
    }
   }
\$\endgroup\$
2
\$\begingroup\$

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)
        }
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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