How to Tweet with Line Break via Fabric(Rest API)


#1

Hello, I’m developing a application for iOS(Swift).
I’m afraid my expressions may be rude or hard to read, because I’m not so good at English.
Sorry for any inconvinience I may cause you.

I’m trying to make tweet with “Line Break”.


For example

Hello!
World!

So I tried to use Rest API via Fabric. But it doesn’t work.

My code is…


let endPoint = "https://api.twitter.com/1.1/statuses/update.json"
var clientError : NSError?

var tweetText = self.contentTextView.text
tweetText = tweetText.stringByReplacingOccurrencesOfString("\n", withString: "\n\r")
let params = ["status" : tweetText]

let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod("POST", URL: endPoint, parameters: params, error: &clientError)

Twitter.sharedInstance().APIClient.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
            if (connectionError == nil) {
                print(“success")
            }else {
                print(“failure: \(connectionError)")
            }
}

In this code, “contentTextView.text" is text which I want to tweet.
I tried to change line break code “\n”,”\r”,”\n\r”,"\r\n" and “%0D%0A”, but it didn’t work too.

Error message is…


failure: Optional(Error Domain=TwitterAPIErrorDomain Code=32 "Request failed: unauthorized (401)" UserInfo={NSErrorFailingURLKey=https://api.twitter.com/1.1/statuses/update.json, NSLocalizedDescription=Request failed: unauthorized (401), NSLocalizedFailureReason=Twitter API error : Could not authenticate you. (code 32)})

If contentTextView.text doesn’t contain “\n” (in other words single line), I can tweet correctly.


For example
Hello! World!

How can I do?

Thanks.


#2

Hi,

I believe you simply need to URL encode your parameters, there are some guides for doing this with Swift like: http://stackoverflow.com/questions/24551816/swift-encode-url

I hope that solves your issue.

Thanks,

John


#3

@JBabichJapan

Thank you for answering my question.

I tried URL encoding.
Using URL encoding, I can tweet with line break correctly!
But tweet result is still wrong.
Do you have any idea?


My code

let encodedText = tweetText.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

let params = ["status" : encodedText!]

let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod("POST", URL: endPoint, parameters: params, error: &clientError)

Twitter.sharedInstance().APIClient.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
    if (connectionError == nil) {
        print("success")
    }else {
        print("failure: \(connectionError)")
    }
}

tweet result

Hello!%0AWorld!


#4

Can you check the implementation upon http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/

I believe the space encoding with the function you are using is what is causing a problem, you might be able to find other articles about this.